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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:42:57  来源:igfitidea点击:

Concatenating two string variables in bash appending newline

linuxbashshell

提问by Aman Deep Gautam

I have a variable final_listwhich is appended by a variable urlin a loop as:

我有一个变量final_list,它由url循环中的变量附加为:

while read url; do
    final_list="$final_list"$'\n'"$url"
done < file.txt

To my surprise the \nis 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". echoit 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"