0

我有一个包含以下行的文件(由空格分隔的 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

我不知道该怎么做。

4

7 回答 7

2

我将使用AWK以下方式,让内容为file.txt

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

然后

awk '{sub(/^.*\//, "", $2);print}' file.txt

输出:

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

解释我只是用空字符串替换感兴趣的列中从开始到最后的所有内容/(因此需要转义),然后是它。\print

(在 GNU Awk 5.0.1 中测试)

于 2020-11-21T12:57:06.197 回答
2

第一个解决方案:您能否尝试使用 GNU 中显示的示例进行跟踪、编写和测试awk

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

第二种解决方案:或仅使用显示的示例尝试将字段分隔符设置为空格或/.

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

第三种解决方案(使用sed):使用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.
于 2020-11-21T12:27:49.240 回答
0

还有这个awk使用循环while

awk '{while ( n=split($2,a,/\//) ) {$2=a[n];print;next}}' file
component1 test 12344
component2 master abcefa123
component3 trunk 72812
component4 integration bc89fa
component5 trunk 989091
component6 test bc7829ac
component7 various eded34512
于 2020-11-22T10:08:52.757 回答
0

使用sed

sed -E 's/^([^ ]* )([^/]*\/)*/\1/' infile
于 2020-11-21T13:03:33.540 回答
0

使用 sed:

sed -rn 's/(^.*)([[:space:]])(.*\/)?(.*)([[:space:]])(.*$)/\1 \4 \6/p' file

根据正则表达式将每一行拆分为多个部分,并将该行替换为相关部分,打印结果。

于 2020-11-21T12:43:37.163 回答
0

使用 awk 的解决方案:

awk '{ split($2,s,"/"); $2=s[length(s)]; print }' inputfile

split($2,s,"/")第二个变量拆分为一个数组

$2=s[length(s)];将用数组的最后一个值分配第二个变量

print将打印完整的行。

于 2020-11-21T12:27:11.273 回答
0
awk '{ split($2,map,"/");$2=map[length(map)] }1' file

使用 awk。使用 / 作为分隔符将第二个空格分隔字段拆分为一个名为 map 的数组。用地图数组的最后一个元素替换 $2。使用速记 1 打印行。

于 2020-11-21T12:27:38.500 回答