linux shell里的substring

一,核心命令

1
2
temp_str="/test/1/2.txt"
echo $temp_str | cut -d'/' -f 1

temp_str使用/splite,并取第1段(index是从1开始,不是0)

二,统计指定字符的出现次数

同上,针对指定路径/test/1/2.txt,我需要去除path,只取文件名2.txt,基本就是substring/即可,在python里可以用rfind,java可以用lastIndexOf,在shell里使用:

1
count=`grep -o '/' <<<${temp_str} | grep -c .`

count需要+1

1
ct=$((count+1))

三,最终,提取文件路径里的文件名

1
2
3
4
5
#先计数
count=`grep -o '/' <<<${temp_str} | grep -c .`
ct=$((count+1))
#再切割
tmp_file_name=$(echo $temp_str| cut -d'/' -f $ct)