使用sed和awk取除最後兩個字段之外的字段
阿新 • • 發佈:2017-08-30
sed
字符串示例為:
/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/ufs-client-2.0.0.jar
需求:如果使用斜杠/作為分隔符的話,可能每個字符串的字段數不同,這時需要取 除了最後兩個字段外的其他字段字符串,所得結果應為如下形式:
/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/
解決方法:
1、使用sed
[[email protected] ~]# b="/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/2.0.0/ufs-client-2.0.0.jar" [[email protected] ~]# 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}‘` [[email protected] ~]# echo $b|sed -n "s#$a##gp" /Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/
2、使用awk
[[email protected] ~]# b="/Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/2.0.0/ufs-client-2.0.0.jar" [[email protected] ~]# echo $b |awk -F‘/‘ ‘{gsub($(NF-1)"/"$NF,"");print}‘ /Users/yfan/Downloads/dsc20170801_jar/releases/com/netfinworks/ufs/ufs-client/
本文出自 “甘木” 博客,請務必保留此出處http://ganmu.blog.51cto.com/9305511/1961162
使用sed和awk取除最後兩個字段之外的字段