简体   繁体   English

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

[英]How to arrange words in a single row using sed or awk?

My file contents: 我的文件内容:

Google
Facebook
yahoo
cisco
juniper
oracle
firetide
attack

I wanted to convert the above words(column) into a row as shown below: 我想将上面的单词(列)转换成一行,如下所示:

Google Facebook yahoo cisco juniper oracle firetide attack

NOTE : There should be a single space between each word. 注意:每个单词之间应该有一个空格。

Please suggest me a way to achieve this using sed or awk. 请建议我使用sed或awk实现此目的的方法。

Thanks in advance. 提前致谢。

Using shell 使用shell

If shell solutions are allowable, then try: 如果shell解决方案是允许的,那么尝试:

$ echo $(cat inputfile) 
Google Facebook yahoo cisco juniper oracle firetide attack

The above should work with any POSIX shell. 以上应适用于任何POSIX shell。 With bash : bash

$ echo $(<inputfile) 
Google Facebook yahoo cisco juniper oracle firetide attack

Using sed 使用sed

If we really must use awk or sed , then here is a sed solution: 如果我们真的必须使用awksed ,那么这里是一个sed解决方案:

$ sed ':a;N;$!ba; s/\n/ /g' inputfile
Google Facebook yahoo cisco juniper oracle firetide attack

The above reads the whole file in ( :a;N;$!ba ) and then replaces all newlines with spaces ( s/\\n/ /g ). 上面用( :a;N;$!ba )读取整个文件,然后用空格( s/\\n/ /g )替换所有换行符。

If the input file might contain extra spaces at the beginning for end of a line, we can remove them: 如果输入文件可能在行的末尾包含额外的空格,我们可以删除它们:

$ sed ':a;N;$!ba; s/[[:space:]]*\n[[:space:]]*/ /g' inputfile
Google Facebook yahoo cisco juniper oracle firetide attack

Using awk 使用awk

$ awk 'ORS=FS' inputFile
Google Facebook yahoo cisco juniper oracle firetide attack 

OR 要么

Another variation would be 另一种变化是

$ awk 1 ORS=' ' input
Google Facebook yahoo cisco juniper oracle firetide attack

Here is another way to do it: 这是另一种方法:

xargs <file
Google Facebook yahoo cisco juniper oracle firetide attack

This also give a newline at the end unlike the awk posted. awk发布的不同,这也在最后给出了换行符。

使用tr

tr '\n' ' ' < File

用awk:

awk '{printf "%s ", $0}' file
sed -n '1h;1!H;${x;s/ *\n */ /gp;}' YourFile
  • 用简单的空格替换起始/结束空间和新行(因此将删除任何起始空间)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM