如果我运行命令cat文件| grep pattern,我将得到许多行输出。如何将所有行连接成一行,有效地将每个“\n”替换为“\”(以“”结尾,后面加空格)?
Cat文件| grep模式| xargs sed s/\n/ /g 对我没用。
如果我运行命令cat文件| grep pattern,我将得到许多行输出。如何将所有行连接成一行,有效地将每个“\n”替换为“\”(以“”结尾,后面加空格)?
Cat文件| grep模式| xargs sed s/\n/ /g 对我没用。
当前回答
可能最好的方法是使用“awk”工具,它将生成输出到一行
$ awk ' /pattern/ {print}' ORS=' ' /path/to/file
它将使用空格分隔符将所有行合并为一行
其他回答
使用tr '\n' ' '将所有换行符转换为空格:
$ grep pattern file | tr '\n' ' '
注:grep读取文件,cat连接文件。不要cat文件| grep!
编辑:
Tr只能处理单个字符的转换。您可以使用awk更改输出记录分隔符,如下所示:
$ grep pattern file | awk '{print}' ORS='" '
这将转化为:
one
two
three
to:
one" two" three"
我喜欢xargs的解决方案,但如果不折叠空格很重要,那么可以这样做:
sed ':b;N;$!bb;s/\n/ /g'
这将为空格替换换行符,而不像tr '\n' ' ' '那样替换最后一行结束符。
这也允许你使用除空格之外的其他连接字符串,比如逗号等,这是xargs无法做到的:
$ seq 1 5 | sed ':b;N;$!bb;s/\n/,/g'
1,2,3,4,5
粘贴-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,
循环地,对于每个' - '的实例。
这可能就是你想要的
cat file | grep pattern | paste -sd' '
至于你的编辑,我不确定是什么意思,也许是这个?
cat file | grep pattern | paste -sd'~' | sed -e 's/~/" "/g'
(这里假设~不会出现在文件中)
通过管道输出到xargs将每一行输出连接到带有空格的一行:
grep pattern file | xargs
或任何命令。Ls | xargs。xargs输出的默认限制是~4096个字符,但是可以使用eg来增加。Xargs -s 8192。
Grep Xargs