仅从文件所有行中的特定字段中删除长前缀? [英] Remove long prefix only from a specific field in all the lines of a file?

查看:25
本文介绍了仅从文件所有行中的特定字段中删除长前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a file containing the following lines (3 fields delimited by space):

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削减其长前缀(与使用$ {string ## *}在bash中所做的相同)并获得以下结果:

I need to manipulate the field 2 to cut its long prefix (same as you do in bash with ${string##*}) and to get the following result:

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 ): 使用 sed ,您可以尝试:

3rd solution(using sed): Using sed, you could try like:

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

说明(第一种解决方案): 为此添加了详细说明.

Explanation(1st solution): Adding detailed explanation for above.

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.

这篇关于仅从文件所有行中的特定字段中删除长前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆