linux awk打印除最后一列外的所有列+最后一列

gmol1639  于 2023-02-11  发布在  Linux
关注(0)|答案(5)|浏览(276)

我有Kafka主题列表,其中有分区编号(最后一位数字,分隔符-)。有些主题的名称中有数字,如topic-with-num-in-name-1

cat /tmp/kafka.txt
topic-with-num-in-name-1-4
topic-without-num-in-name-3

问:我如何打印消息像
"主题:名称中有编号的主题-1"及其分区号:* * 4**"

"主题:名称中没有数字的主题"及其分区号:* * 3**"?
我是这样试的:

cat /tmp/kafka.txt | awk 'BEGIN{FS=OFS="-"}{NF--;}{print}'

但只能打印主题名称:

topic-with-num-in-name-1
topic-without-num-in-name

谢谢!

blmhpbnm

blmhpbnm1#

一个简单的sed与贪婪正则表达式匹配:

sed -E 's/(.+)-(.+)/Topic: \1 and his partition number: \2/' kafka.txt

Topic: topic-with-num-in-name-1 and his partition number: 4
Topic: topic-without-num-in-name and his partition number: 3
3yhwsihp

3yhwsihp2#

使用基于FS的提取:

awk -F- '{ printf "\"Topic: %s\" and his partition number: %s\n", $0, $NF }' file
y53ybaqx

y53ybaqx3#

使用以下awk命令:

$ awk 'BEGIN{ FS=OFS="-" }{ n=$(NF); NF--; print $0" "n}' kafka.txt
topic-with-num-in-name-1 4
topic-without-num-in-name 3
w1jd8yoj

w1jd8yoj4#

$ awk '{print gensub(/-([^-]*$)/," \\1",1)}' inputfile 
topic-with-num-in-name-1 4
topic-without-num-in-name 3

$ sed -r 's/(.*)-/\1 /' inputfile 
topic-with-num-in-name-1 4
topic-without-num-in-name 3

$ cat inputfile | rev | sed 's/-/ /' | rev
topic-with-num-in-name-1 4
topic-without-num-in-name 3
zaq34kh6

zaq34kh65#

使用您展示的示例和尝试,请尝试以下GNU awk代码。

awk '
match($0,/(^.*)-(.*)$/,arr){
   print "Topic: " arr[1] " and his partition number: " arr[2]
}
' Input_file

相关问题