如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
如何使用sed命令将换行符(“\n”)替换为空格(“”)?
我尝试过:
sed 's#\n# #g' file
sed 's#^$# #g' file
如何修复?
当前回答
也可以使用此方法:
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并打印确切结果。
其他回答
sed旨在用于基于行的输入。尽管它可以满足你的需要。
这里更好的选择是使用tr命令,如下所示:
tr '\n' ' ' < input_filename
或完全删除换行符:
tr -d '\n' < input.txt > output.txt
或者如果您有GNU版本(带有长选项)
tr --delete '\n' < input.txt > output.txt
针对上述“tr”解决方案,在Windows上(可能使用Gnuwin32版本的tr),建议的解决方案:
tr '\n' ' ' < input
对我不起作用,它可能会出错,或者出于某种原因实际上替换了\n w/“”。
使用tr的另一个功能,“delete”选项-d确实有效:
tr -d '\n' < input
或“\r\n”而不是“\n”
Perl版本以您预期的方式工作。
perl -i -p -e 's/\n//' file
正如评论中所指出的,值得注意的是,这些编辑是到位的-i.bak将在替换之前为您提供原始文件的备份,以防您的正则表达式没有您想象的那么聪明。
是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~$
为什么我没有找到一个简单的awk解决方案?
awk '{printf $0}' file
printf将打印没有换行的每一行,如果您想用空格或其他分隔原始行:
awk '{printf $0 " "}' file