如果我运行命令cat文件| grep pattern,我将得到许多行输出。如何将所有行连接成一行,有效地将每个“\n”替换为“\”(以“”结尾,后面加空格)?

Cat文件| grep模式| xargs sed s/\n/ /g 对我没用。


当前回答

下面是使用ex编辑器(Vim的一部分)的方法:

连接所有行并打印到标准输出: $ x +%j +%p -scq!文件 (在文件中)原位连接所有行: $ ex +%j -scwq文件 注意:这将连接文件内部的所有行!

其他回答

粘贴-sd ` ~ `出错。

下面是我在使用bash的mac上使用的方法

cat file | grep pattern | paste -d' ' -s -

从男人膏。

-d list     Use one or more of the provided characters to replace the newline characters instead of the default tab.  The characters
                 in list are used circularly, i.e., when list is exhausted the first character from list is reused.  This continues until
                 a line from the last input file (in default operation) or the last line in each file (using the -s option) is displayed,
                 at which time paste begins selecting characters from the beginning of list again.

                 The following special characters can also be used in list:

                 \n    newline character
                 \t    tab character
                 \\    backslash character
                 \0    Empty string (not a null character).

                 Any other character preceded by a backslash is equivalent to the character itself.

     -s          Concatenate all of the lines of each separate input file in command line order.  The newline character of every line
                 except the last line in each input file is replaced with the tab character, unless otherwise specified by the -d option.
                 If ‘-’ is specified for one or more of the input files, the standard input is used; standard input is read one line at a time,  

循环地,对于每个' - '的实例。

在不带引号的bash echo中,删除回车符、制表符和多个空格

echo $(cat file)

在red hat linux上,我只使用echo:

Echo $(cat /some/file/name)

这将在一行中给出文件的所有记录。

下面是另一个使用awk的简单方法:

# cat > file.txt
a
b
c

# cat file.txt | awk '{ printf("%s ", $0) }'
a b c

此外,如果你的文件有列,这提供了一个简单的方法来连接某些列:

# cat > cols.txt
a b c
d e f

# cat cols.txt | awk '{ printf("%s ", $2) }'
b e

通过管道输出到xargs将每一行输出连接到带有空格的一行:

grep pattern file | xargs

或任何命令。Ls | xargs。xargs输出的默认限制是~4096个字符,但是可以使用eg来增加。Xargs -s 8192。

Grep Xargs