用 bash 中的空格替换 \n(新行)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39198780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace \n(new line) with space in bash
提问by Prometheus
I am reading some sql queries into a variable from db and it contains new line character (\n). I want to replace \n (new line) with space. I tried solutions provided on internet but was unsuccessful to achieve what I want. Here is what tried :
我正在从 db 中读取一些 sql 查询到一个变量中,它包含换行符 (\n)。我想用空格替换 \n (新行)。我尝试了互联网上提供的解决方案,但没有成功实现我想要的。这是尝试过的:
strr="my\nname\nis\nxxxx";
nw_strr=`echo $strr | tr '\n' ' '`;
echo $nw_strr;
my desired output is "my name is xxxx" but what I am getting is "my\nname\nis\nxxxx". I also tried other solution provided at internet, but no luck:
我想要的输出是“我的名字是 xxxx”,但我得到的是“我的\nname\nis\nxxxx”。我还尝试了互联网上提供的其他解决方案,但没有运气:
nw_strr=`echo $strr | sed ':a;N;$!ba;s/\n/ /g'`;
Am I doing something wong?
我在做什么吗?
回答by Cyrus
With bash:
使用 bash:
Replace all newlines with a space:
用空格替换所有换行符:
nw_strr="${strr//$'\n'/ }"
Replace all strings \n
with a space:
用\n
空格替换所有字符串:
nw_strr="${strr//\n/ }"