字符串示例为:

1
/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/ufs-client-2.0.0.jar

需求:如果使用斜杠/作为分隔符的话,可能每个字符串的字段数不同,这时需要取 除了最后两个字段外的其他字段字符串,所得结果应为如下形式:

1
/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/


解决方法:

1、使用sed

1
2
3
4
[root@www ~]# b="/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/2.0.0/ufs-client-2.0.0.jar"
[root@www ~]# a=`echo "/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/2.0.0/ufs-client-2.0.0.jar" |awk -F'/' '{print $(NF-1)"/"$NF}'`
[root@www ~]# echo $b|sed -n "s#$a##gp"
/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/


2、使用awk

1
2
3
[root@www ~]# b="/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/2.0.0/ufs-client-2.0.0.jar"
[root@www ~]# echo $b |awk -F'/' '{gsub($(NF-1)"/"$NF,"");print}'
/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/