bash 如何使用“sed或awk”从bash中的行中删除最后一个逗号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39285636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove last comma from line in bash using "sed or awk"
提问by P....
Hi I want to remove last comma from a line. For example:
嗨,我想从一行中删除最后一个逗号。例如:
Input:
输入:
This,is,a,test
Desired Output:
期望输出:
This,is,a test
I am able to remove last comma if its also the last character of the string using below command: (However this is not I want)
如果最后一个逗号也是使用以下命令的字符串的最后一个字符,我可以删除最后一个逗号:(但这不是我想要的)
echo "This,is,a,test," |sed 's/,$//'
This,is,a,test
Same command does not work if there are more characters past last comma in line.
如果行中最后一个逗号之后有更多字符,则相同的命令将不起作用。
echo "This,is,a,test" |sed 's/,$//'
This,is,a,test
I am able to achieve the results using dirty way by calling multiple commands, any alternative to achieve the same using awk or sed regex ?(This is I want)
我可以通过调用多个命令使用脏方式获得结果,使用 awk 或 sed regex 实现相同的任何替代方法?(这是我想要的)
echo "This,is,a,test" |rev |sed 's/,/ /' |rev
This,is,a test
回答by merlin2011
You can use a regex that matches not-comma, and captures that group, and then restores it in the replacement.
您可以使用匹配非逗号的正则表达式,并捕获该组,然后在替换中恢复它。
echo "This,is,a,test" |sed 's/,\([^,]*\)$/ /'
Output:
输出:
This,is,a test
回答by Sundeep
$ echo "This,is,a,test" | sed 's/\(.*\),/ /'
This,is,a test
with lookbehind,
回头看,
$ echo "This,is,a,test" | perl -pe 's/.*\K,/ /'
This,is,a test
*
is greedy, tries to match as much as possible.
*
是贪婪的,尝试尽可能多地匹配。
回答by anubhava
All the answer are based on regex. Here is a non-regex way to remove last comma:
所有的答案都基于正则表达式。这是删除最后一个逗号的非正则表达式方法:
s='This,is,a,test'
awk 'BEGIN{FS=OFS=","} {$(NF-1)=$(NF-1) " " $NF; NF--} 1' <<< "$s"
This,is,a test
回答by John B
One way to do this is by using Bash Parameter Expansion.
一种方法是使用Bash Parameter Expansion。
$ s="This,is,a,test"
$ echo "${s%,*} ${s##*,}"
This,is,a test
回答by James Brown
In Gnu AWK too since tagged:
在 Gnu AWK 中也有标记:
$ echo This,is,a,test|awk '##代码##=gensub(/^(.*),/,"\1 ","g",##代码##)'
This,is,a test