在Linux shell中,我有一个字符串,其中包含以下内容:
cat
dog
bird
Run Code Online (Sandbox Code Playgroud)
我想将每个项目作为参数传递给另一个函数.我怎样才能做到这一点?
osg*_*sgx 50
使用它(它是从文件中读取每一行的循环file)
cat file | while read -r a; do echo $a; done
Run Code Online (Sandbox Code Playgroud)
在echo $a任何你想要的当前行做的是.
更新:来自评论员(谢谢!)
如果没有多行文件,但有多行变量,请使用
echo "$variable" | while read -r a; do echo $a; done
Run Code Online (Sandbox Code Playgroud)
UPDATE2:" read -r"建议禁用backslashed(\)字符解释(检查mtraceur注释;大多数shell支持).它在POSIX 1003.1-2008中有记录http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html
默认情况下,除非指定-r选项,否则
<backslash>应充当转义字符...支持以下选项:-r- 不要<backslash>以任何特殊方式处理字符.考虑每个都是输入行的一部分.
只需将您的字符串传递给您的函数:
function my_function
{
while test $# -gt 0
do
echo "do something with $1"
shift
done
}
my_string="cat
dog
bird"
my_function $my_string
Run Code Online (Sandbox Code Playgroud)
给你:
do something with cat
do something with dog
do something with bird
Run Code Online (Sandbox Code Playgroud)
如果你真的关心其他空格被当作参数分隔符,首先设置你的IFS:
IFS="
"
my_string="cat and kittens
dog
bird"
my_function $my_string
Run Code Online (Sandbox Code Playgroud)
要得到:
do something with cat and kittens
do something with dog
do something with bird
Run Code Online (Sandbox Code Playgroud)
unset IFS之后别忘了.
如果你使用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
Run Code Online (Sandbox Code Playgroud)