从两个/右边提取字符串

时间:2015-03-17 06:01:55

标签: linux bash awk sed scripting

从两个/右边提取字符串

指挥准备:

输入: - [目录名称不恒定]

示例1: -

/dir1/dir2/

示例2: -

/dir1/dir2/dir3/dir4/

我希望输出如下

示例1输出: -

nohup dsmc arch /dir1/dir2/ -subdir=yes > /tsm/backuplogs/dir2_`date +%d%m%y_%H_%M`.log &

示例2输出: -

nohup dsmc arch /dir1/dir2/dir3/dir4/ -subdir=yes > /tsm/backuplogs/dir4_`date +%d%m%y_%H_%M`.log &

2 个答案:

答案 0 :(得分:4)

尝试这样来提取子字符串:

basename /dir1/dir2/dir3/dir4/

输出:

dir4

使用bash内置命令:

string="/dir1/dir2/dir3/dir4/"
string="${string%/*}"           # remove trailing /
echo "${string##*/}"            # remove /dir1/dir2/dir3/

输出

dir4

答案 1 :(得分:3)

使用basename程序从路径中提取最后一个目录,如下所示:

path=/dir1/dir2/dir3/dir4/
echo "nohup dsmc arch $path -subdir=yes > /tsm/backuplogs/$(basename $path)_\`date +%d%m%y_%H_%M\`.log &" 

以上行将输出:

nohup dsmc arch /dir1/dir2/dir3/dir4/ -subdir=yes > /tsm/backuplogs/dir4_`date +%d%m%y_%H_%M`.log &