bash 从 shell 脚本中的变量中逐行读取
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11902177/
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
Read line by line from a variable in shell scripting
提问by sasidhar
I have a script variable which is multi-line. How do i traverse this variable to read it line by line and process each line the way I want?
我有一个多行的脚本变量。我如何遍历这个变量来逐行读取它并按照我想要的方式处理每一行?
回答by Karoly Horvath
Consider the following multi-line variable
考虑以下多行变量
x=$(echo -e "a\nb\nc d e")
and a simple process for each line: just echo
it with a prefix=LINE:
and with single quotes around the line. Either of the following codes will satisfy that requirement:
每行都有一个简单的过程:只是echo
它带有一个前缀=LINE:
并在该行周围加上单引号。以下任一代码都将满足该要求:
while read line; do echo "LINE: '${line}'"; done <<< "$x"
or
或者
while read line; do echo "LINE: '${line}'"; done < <(echo "$x")
Neither creates a subshell (so you can, e.g., set variables in the loop and access them outside of it), and both output
两者都不创建子shell(因此您可以,例如,在循环中设置变量并在循环外部访问它们),并且两个输出
LINE: 'a'
LINE: 'b'
LINE: 'c d e'
But suppose instead you have
但假设你有
x=$(echo -e "a \n b\nc d e")
# note--------^--^
and that leading and trailing whitespace matter for your application (e.g., parsing Git porcelain). Both the above codes will give exactly the same output for the latter variable/data as for the former, which is not what you want. To preserve leading and trailing whitespace, replace while read line
with while IFS= read -r line
. I.e., either of the following codes
并且前导和尾随空格对您的应用程序很重要(例如,解析 Git 瓷器)。上述两个代码将为后一个变量/数据提供与前一个完全相同的输出,这不是您想要的。要保留前导和尾随空格,请替换while read line
为while IFS= read -r line
. 即,以下任一代码
while IFS= read -r line; do echo "LINE: '${line}'"; done <<< "$x"
or
或者
while IFS= read -r line; do echo "LINE: '${line}'"; done < <(echo "$x")
will produce
会产生
LINE: 'a '
LINE: ' b'
LINE: 'c d e'
See Greg Wooledge's excellent Bash FAQfor details.
有关详细信息,请参阅Greg Wooledge 出色的 Bash 常见问题解答。
回答by Seth McCauley
Although I typically use "while read" for processing multi-line variables, I recently had an instance where it removed the leading space from each line in a file. Using this instead fixed my issue:
尽管我通常使用“while read”来处理多行变量,但我最近有一个实例,它删除了文件中每一行的前导空格。使用它来解决我的问题:
printf %s "$var" | while IFS= read -r line
do
echo "$line"
done
Code taken from this Unix Stack Exchange answer.