Linux 将多行转换为以逗号分隔的一行 (Perl/Sed/AWK)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15758814/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:37:46  来源:igfitidea点击:

Turning multiple lines into one line with comma separated (Perl/Sed/AWK)

linuxperlunixsedawk

提问by neversaint

I have the following data in multiple lines:

我在多行中有以下数据:

foo
bar
qux
zuu
sdf
sdfasdf

What I want to do is to convert them with one line and comma separated:

我想要做的是用一行和逗号分隔来转换它们:

foo,bar,qux,zuu,sdf,sdfasdf

What's the best unix one-liner to do that?

什么是最好的 unix one-liner 来做到这一点?

采纳答案by Guru

Using paste command:

使用粘贴命令:

paste -d, -s file

回答by n3rV3

There are many ways it can be achieved. The tool you use mostly depends on your own preference or experience.

有很多方法可以实现。您使用的工具主要取决于您自己的偏好或经验。

Using tr command:

使用 tr 命令:

tr '\n' ',' < somefile

Using awk:

使用 awk:

awk -F'\n' '{if(NR == 1) {printf 
perl -pe'chomp, s/$/,/ unless eof' file
} else {printf ","
perl '-peeof||chomp&&s/$/,/' file
}}' somefile

回答by choroba

Perl one-liner:

Perl 单行:

awk -vRS="" -vOFS=',' '=' file

or, if you want to be more cryptic:

或者,如果你想更神秘:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '=' 
foo,bar,qux,zuu,sdf,sdfasdf

回答by Kent

based on your input example, this awk line works. (without trailing comma)

根据您的输入示例,此 awk 行有效。(不带尾随逗号)

perl -pi.bak -e 'unless(eof){s/\n/,/g}' your_file

test:

测试:

sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)//;$s/\(.*\),//;$p'

回答by Vijay

aaa
bbb
ccc
ddd

This will create a backup of original file with an extension of .bak and then modifies the original file

这将创建扩展名为 .bak 的原始文件的备份,然后修改原始文件

回答by protist

cat file | xargs

回答by Serhii Kuzmychov

file

文件

aaa bbb ccc ddd 

xargs

参数

cat file | xargs | sed -e 's/ /,/g'

result

结果

aaa,bbb,ccc,ddd 

xargs improoved

xargs 改进

##代码##

result

结果

##代码##

回答by Serhii Kuzmychov

xargs -a your_file | sed 's/ /,/g'

xargs -a your_file | sed 's/ /,/g'

This is a shorter way.

这是一种较短的方式。