如何使用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并打印确切结果。
其他回答
使用Awk:
awk "BEGIN { o=\"\" } { o=o \" \" \$0 } END { print o; }"
这真的很简单。。。当我找到解决办法时,我真的很生气。又少了一个反斜杠。这就是:
sed -i "s/\\\\\n//g" filename
在sed替换部分中,键入反斜杠,按回车键转到第二行,然后以/g'结尾:
sed 's/>/\
/g'
[root@localhost ~]# echo "1st</first>2nd</second>3rd</third>" | sed 's/>/\
> /g'
1st</first
2nd</second
3rd</third
[root@localhost ~]#
是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~$
谁需要sed?以下是bash方式:
cat test.txt | while read line; do echo -n "$line "; done