gpt4 book ai didi

awk - 拆分列后如何找到LAST子字段

转载 作者:行者123 更新时间:2023-12-04 13:49:28 24 4
gpt4 key购买 nike

我试图在应用拆分后获取字符串的最后一个子字段。当我不知道吐出的结果中最后一个字段的值是什么时,问题就出现了。

例如示例数据

hey,there,how,are,you:bla:bla:foo:bar
hey,this,is ,meaningless,text,and ,the,field,are,more:zoo,zoo
hello,folks,thanks,example:is:this:is:a:line:and:I:could:not:think:of:dummy:data

现在我可以使用 NF 获取最后一个字段。

例子:

awk -F, '{print $NF}' input
you:bla:bla:foo:bar
more:zoo,zoo
example:is:this:is:a:line:and:I:could:not:think:of:dummy:data

现在,如果我可以使用 split 函数获取任何字段:

awk -F, '{split($NF,a,":");print a[1]}' input
you
more
example

现在我不需要第N个字段,我需要提取第N个字段的LAST子字段。

所以我想要的输出是:

bar
zoo
data

请注意,以下内容没有有帮助,因为这仅对最后一列有帮助。

sed -r 's/(^.*:)(.*)/\2/g' inut
bar
zoo
data

最佳答案

使用split()函数的返回值作为数组下标,

awk -F, '{n=split($NF,a,":");print a[n]}' file
bar
zoo
data

返回值是由分隔符:拆分的字段数,您可以将其应用于您选择的任何字符。

引自GNU Awk split() 函数的页面

split(string, array [, fieldsep [, seps ] ])

If fieldsep is a single space, then any leading whitespace goes into seps[0] and any trailing whitespace goes into seps[n], where n is the return value of split() (i.e., the number of elements in array).

关于awk - 拆分列后如何找到LAST子字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42971431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com