如何使用sed或awk在单行中排列单词?

Kum*_*mar 2 awk sed

我的文件内容:

Google
Facebook
yahoo
cisco
juniper
oracle
firetide
attack
Run Code Online (Sandbox Code Playgroud)

我想将上面的单词(列)转换成一行,如下所示:

Google Facebook yahoo cisco juniper oracle firetide attack
Run Code Online (Sandbox Code Playgroud)

注意:每个单词之间应该有一个空格.

请建议我使用sed或awk实现此目的的方法.

提前致谢.

Joh*_*024 5

使用shell

如果shell解决方案是允许的,那么尝试:

$ echo $(cat inputfile) 
Google Facebook yahoo cisco juniper oracle firetide attack
Run Code Online (Sandbox Code Playgroud)

以上应适用于任何POSIX shell.用bash:

$ echo $(<inputfile) 
Google Facebook yahoo cisco juniper oracle firetide attack
Run Code Online (Sandbox Code Playgroud)

运用 sed

如果我们真的必须使用awksed,那么这里是一个sed解决方案:

$ sed ':a;N;$!ba; s/\n/ /g' inputfile
Google Facebook yahoo cisco juniper oracle firetide attack
Run Code Online (Sandbox Code Playgroud)

上面用(:a;N;$!ba)读取整个文件,然后用空格(s/\n/ /g)替换所有换行符.

如果输入文件可能在行的末尾包含额外的空格,我们可以删除它们:

$ sed ':a;N;$!ba; s/[[:space:]]*\n[[:space:]]*/ /g' inputfile
Google Facebook yahoo cisco juniper oracle firetide attack
Run Code Online (Sandbox Code Playgroud)