如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
当前回答
我特别喜欢的解决方案是在保留空间中追加所有文件,并替换文件末尾的所有换行符:
$ (echo foo; echo bar) | sed -n 'H;${x;s/\n//g;p;}'
foobar
然而,有人告诉我,在一些sed实现中,保持空间可能是有限的。
其他回答
是sed在“正常”替换之后引入了新的行。首先,它修剪新行字符,然后根据您的指示进行处理,然后引入新行。
使用sed,您可以为每个输入行用您选择的字符串替换修剪后的行(而不是新行字符)的“结尾”;但是,sed将输出不同的行。例如,假设您希望将“行尾”替换为“==”(比用单个空格替换更通用):
PROMPT~$ cat <<EOF |sed 's/$/===/g'
first line
second line
3rd line
EOF
first line===
second line===
3rd line===
PROMPT~$
要用字符串替换新行字符,可以低效地使用tr,如前所述,用“特殊字符”替换换行字符,然后使用sed用所需的字符串替换该特殊字符。
例如:
PROMPT~$ cat <<EOF | tr '\n' $'\x01'|sed -e 's/\x01/===/g'
first line
second line
3rd line
EOF
first line===second line===3rd line===PROMPT~$
可以使用xargs:
seq 10 | xargs
or
seq 10 | xargs echo -n
您可以使用xargs-默认情况下,它将用空格替换\n。
但是,如果您的输入有任何未终止的引号,例如给定行上的引号符号不匹配,则会出现问题。
还有一种选择:
tr-s“[:space:]”“”<filename>filename2&&mv filename2文件名
其中tr-s表示:
-s、 --挤压重复替换重复字符的每个序列其列在最后指定的SET中,只出现一次该字符
这将使用单个空格替换文件中的所有空格序列,将结果写入新文件,然后将新文件重命名为原始名称。
也可以使用此方法:
sed 'x;G;1!h;s/\n/ /g;$!d'
解释
x - which is used to exchange the data from both space (pattern and hold).
G - which is used to append the data from hold space to pattern space.
h - which is used to copy the pattern space to hold space.
1!h - During first line won't copy pattern space to hold space due to \n is
available in pattern space.
$!d - Clear the pattern space every time before getting the next line until the
the last line.
Flow
当第一行从输入中获取时,进行交换,因此1进入保留空间,\n进入模式空间,将保留空间附加到模式空间,执行替换并删除模式空间。
在第二行中,进行交换,2到保持空间,1到模式空间,G将保持空间附加到模式空间中,h将模式复制到其中,进行替换并删除。此操作将继续,直到达到EOF并打印确切结果。