sed,除了最后一个标识符列表中的匹配词(标识符)

艾尔芬·露

给出以下格式的标识符列表:

test_one another_one lol heres1 wow_the_last

我正在尝试使用sed将其替换为以下任何一种:

test_one,another_one,lol,heres1
test_one, another_one, lol, heres1
{test_one, another_one, lol, heres1}
{test_one,another_one,lol,heres1}

我能够使用以下sed命令执行此操作:

sed -e 's/\(\w*\)\s/\1,/g'

但我希望找到一种更可靠的解决方案,该解决方案不依赖于列表中的最后一个字尾没有空格。相反,我试图使匹配基于不在行尾或后面紧跟另一个单词。但是我在这个方向上的尝试要么没有匹配,要么匹配太多。

sed -e 's/\(\w*\)^$/\1,/g'
sed -e 's/\(\w*\)[^$]/\1,/g'

我尝试了上面的方法,但是第一个似乎不匹配任何内容,而下面的一个则产生以下内容:

test_one,another_one,lol,heres,
詹姆斯·布朗

不确定我是否正确理解您,但是使用awk:

$ awk 'BEGIN{OFS=","}{$1=$1;NF--;print}' file
test_one,another_one,lol,heres1

解释:

$ awk '
BEGIN { OFS="," }  # set the output field separator to a comma
{
    $1=$1          # rebuild the record, ie. use the commas
    NF--           # reduce field count by one
    print          # output
}' file

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章