仅从文件所有行中的特定字段中删除长前缀? [关闭]

2024-07-04

我有一个包含以下几行的文件(由空格分隔的 3 个字段):

component1 /dev/user/test 12344
component2 master abcefa123
component3 trunk 72812
component4 /branch/user/integration bc89fa
component5 trunk 989091 
component6 integration/test bc7829ac
component7 /branch/dev/user/various eded34512

我需要操作字段 2 以剪切其长前缀(与在 bash 中使用 ${string##*} 所做的相同)并获得以下结果:

component1 test 12344
component2 master abcefa123
component3 trunk 72812
component4 integration bc89fa
component5 trunk 989091 
component6 test bc7829ac
component7 various eded34512

我不知道该怎么做。


第一个解决方案:您能否尝试按照 GNU 中所示的示例进行编写和测试awk.

awk '{num=split($2,arr,"/");$2=arr[num]} 1' Input_file

第二个解决方案:或者对于显示的示例,仅尝试将字段分隔符设置为空格或/.

awk -F'[ /]' '{print $1,$(NF-1),$NF}' Input_file

第三种解决方案(使用sed): Using sed,你可以尝试像:

sed 's/\([^ ]*\).*\/\(.*\)/\1 \2/' Input_file

解释(第一个解决方案):对上述内容添加详细解释。

awk '                   ##Starting awk program from here.
{
  num=split($2,arr,"/") ##Splitting 2nd field into array arr with / as field separator.
                        ##num is number of total elements of array arr.
  $2=arr[num]           ##Assigning last element of arr with index of num into 2nd field.
}
1                       ##Mentioning 1 will print the current line.
' Input_file            ##mentioning Input_file name here.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅从文件所有行中的特定字段中删除长前缀? [关闭] 的相关文章

随机推荐