Sed,匹配标识符列表中除最后一个之外的单词(标识符)

Sed,匹配标识符列表中除最后一个之外的单词(标识符),sed,command-line,Sed,Command Line,给出以下格式的标识符列表: 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} test_one,another_one,lol,here

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

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}
test_one,another_one,lol,heres,
我可以使用以下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,heres1
test_one, another_one, lol, heres1
{test_one, another_one, lol, heres1}
{test_one,another_one,lol,heres1}
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

它必须是sed吗?因为
perl-anle'pop@F;打印join“,”,@F'
@melpomene我有可用的perl,但这实际上不起作用。它排除了最后一个词。我希望输出列表中的所有单词,除最后一个单词外,所有单词之间都添加逗号