微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Linux shell中,如何处理多行string的每一行?

而在Linux shell中,我有一个string,其内容如下:

cat dog bird

我想将每个项目作为parameter passing给另一个函数。 我怎样才能做到这一点?

输出转换为string

重复udp数据包:发生多less次?

用于subprocess的SIGTSTP信号处理程序

Erlang的shell问题

JavaFX从JDK 1.7 / 1.8在Linux中缺less?

使用这个(它是从文件file中读取每一行的循环)

cat file | while read -ra; do echo $a; done

echo $a就是你想要用当前行做的任何事情。

更新:从评论员(谢谢!)

如果您没有多行文件,但是有多行的变量,请使用

echo "$variable" | while read -ra; 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>字符。 考虑每一个都是输入行的一部分。

只要把你的字符串传给你的函数

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 。

如果你使用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

使用while循环read :

while read line; do echo $line; done

使用xargs :

根据你想要做的每一行,它可以像这样简单:

xargs -n1 func < file

或更复杂的使用:

cat file | xargs -n1 -I{} func {}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐