英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论