在Linux shell中,我有一个字符串,其中包含以下内容:
cat
dog
bird
我希望将每个项目作为参数传递给另一个函数。我怎么能这样做?
答案 0 :(得分:48)
使用它(它是从文件file
读取每一行的循环)
cat file | while read -r a; do echo $a; done
echo $a
是你想用当前行做的任何事情。
更新:来自评论员(谢谢!)
如果没有多行文件,但有多行变量,请使用
echo "$variable" | while read -r a; do echo $a; done
UPDATE2:建议“read -r
”禁用反斜杠(\
)字符解释(检查mtraceur注释;大多数shell支持)。它记录在POSIX 1003.1-2008 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html
默认情况下,除非指定了-r选项,否则
<backslash>
将充当转义字符。 ..支持以下选项:-r
- 不要以任何特殊方式处理<backslash>
字符。考虑每个都是输入行的一部分。
答案 1 :(得分:7)
只需将字符串传递给您的函数:
function my_function
{
while test $# -gt 0
do
echo "do something with $1"
shift
done
}
my_string="cat
dog
bird"
my_function $my_string
给你:
do something with cat
do something with dog
do something with bird
如果您真的关心将其他空格作为参数分隔符,请先设置IFS
:
IFS="
"
my_string="cat and kittens
dog
bird"
my_function $my_string
得到:
do something with cat and kittens
do something with dog
do something with bird
在此之后不要忘记unset IFS
。
答案 2 :(得分:6)
如果您使用bash,只需设置IFS:
$ x="black cat
brown dog
yellow bird"
$ IFS=$'\n'
$ for word in $x; do echo "$word"; done
black cat
brown dog
yellow bird
答案 3 :(得分:3)
使用xargs
:
根据您对每一行的要求,它可以简单如下:
xargs -n1 func < file
或更复杂的使用:
cat file | xargs -n1 -I{} func {}
答案 4 :(得分:2)
使用read
和while循环:
while read line; do
echo $line;
done
答案 5 :(得分:1)
这样做:
multrs="some multiple line string ...
...
..."
while read -r line; do
echo $line;
done <<< "$mulstrs"
变量$ mulstr必须用双引号括住,否则空格或回车会干扰计算。