Linux 在bash追加换行符中连接两个字符串变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18535902/
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
Concatenating two string variables in bash appending newline
提问by Aman Deep Gautam
I have a variable final_list
which is appended by a variable url
in a loop as:
我有一个变量final_list
,它由url
循环中的变量附加为:
while read url; do
final_list="$final_list"$'\n'"$url"
done < file.txt
To my surprise the \n
is appended as an space, so the result is:
令我惊讶的\n
是,它被附加为一个空格,所以结果是:
url1 url2 url3
while I wanted:
虽然我想要:
url1
url2
url3
What is wrong?
怎么了?
采纳答案by anubhava
New lines are very much there in the variable "$final_list"
. echo
it like this with double quotes:
变量中有很多新行"$final_list"
。echo
它像这样带双引号:
echo "$final_list"
url1
url2
url3
OR better use printf
:
或更好地使用printf
:
printf "%s\n" "$final_list"
url1
url2
url3
回答by Emo Mosley
It may depend on how you're trying to display the final result. Try outputting the resulting variable within double-quotes:
这可能取决于您尝试显示最终结果的方式。尝试在双引号内输出结果变量:
echo "$final_list"