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

huangapple go评论64阅读模式
英文:

awk print all but last column + last column

问题

"Topic: topic-with-num-in-name-1" and his partition number: 4"

or

"Topic: topic-without-num-in-name" and his partition number: 3"

英文:

I have kafka topics list with them partition numbers(last digit, delimiter -).
Some topics have digit in names like topic-with-num-in-name-1.

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

Q:
How i can print message like

"Topic: topic-with-num-in-name-1" and his partition number: 4"

or

"Topic: topic-without-num-in-name" and his partition number: 3"
?

I tried like this:

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

but can only print topic name:

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

Thanks!

答案1

得分: 5

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

英文:

A simple sed with a greedy regex matching:

sed -E 's/(.+)-(.+)/Topic:  and his partition number: /' 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

答案2

得分: 2

使用基于FS的提取:

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

Using FS-based extraction:

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

答案3

得分: 2

使用以下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
英文:

Use the following awk command:

$ 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

答案4

得分: 2

$ 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

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

$ sed -r 's/(.*)-/ /' 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

答案5

得分: 2

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

```awk
awk '
match($0,/(^.*)-(.*)$/,arr){
   print "主题: " arr[1] " 和他的分区号: " arr[2]
}
' Input_file

<details>
<summary>英文:</summary>

With your shown samples and attempts please try following GNU `awk` code.


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


</details>



huangapple
  • 本文由 发表于 2023年2月10日 04:25:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定