【问题标题】:Sed, match words (identifiers) in a list of identifiers except the lastsed,匹配标识符列表中的单词(标识符),除了最后一个
【发布时间】:2018-05-08 08:34:01
【问题描述】:

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

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,

【问题讨论】:

  • 必须是sed吗?因为perl -anle 'pop @F; print join ", ", @F'.
  • @melpomene 我有可用的 perl,但这实际上不起作用。它不包括最后一个词。我希望输出列表中的所有单词,并在除最后一个单词之外的所有单词之间添加逗号

标签: sed command-line


【解决方案1】:

不确定我是否理解正确,但使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多