In a Linux shell how can I process each line of a

2020-05-17 05:16发布

While in a Linux shell I have a string which has the following contents:

cat
dog
bird

and I want to pass each item as an argument to another function. How can I do this?

标签: linux shell
6条回答
ら.Afraid
2楼-- · 2020-05-17 05:38

Just pass your string to your function:

function my_function
{
    while test $# -gt 0
    do
        echo "do something with $1"
        shift
    done
}
my_string="cat
dog
bird"
my_function $my_string

gives you:

do something with cat
do something with dog
do something with bird

And if you really care about other whitespaces being taken as argument separators, first set your IFS:

IFS="
"
my_string="cat and kittens
dog
bird"
my_function $my_string

to get:

do something with cat and kittens
do something with dog
do something with bird

Do not forget to unset IFS after that.

查看更多
女痞
3楼-- · 2020-05-17 05:43

if you use bash, setting IFS is all you need:

$ x="black cat
brown dog
yellow bird"
$ IFS=$'\n'
$ for word in $x; do echo "$word"; done
black cat
brown dog
yellow bird
查看更多
再贱就再见
4楼-- · 2020-05-17 05:44

Use read with a while loop:

while read line; do
    echo $line;
done
查看更多
一夜七次
5楼-- · 2020-05-17 05:48

Use this (it is loop of reading each line from file file)

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

where the echo $a is whatever you want to do with current line.

UPDATE: from commentators (thanks!)

If you have no file with multiple lines, but have a variable with multiple lines, use

echo "$variable" | while read -r a; do echo $a; done

UPDATE2: "read -r" is recommended to disable backslashed (\) chars interpretation (check mtraceur comments; supported in most shells). It is documented in POSIX 1003.1-2008 http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html

By default, unless the -r option is specified, <backslash> shall act as an escape character. .. The following option is supported: -r - Do not treat a <backslash> character in any special way. Consider each to be part of the input line.

查看更多
劫难
6楼-- · 2020-05-17 05:48

Do like this:

multrs="some multiple line string ...
...
..."

while read -r line; do
    echo $line;
done <<< "$mulstrs"

Variable $mulstrs must be enclosed in double quotes, otherwise spaces or carriage returns will interfere with the calculation.

查看更多
Luminary・发光体
7楼-- · 2020-05-17 05:53

Use xargs:

Depending on what you want to do with each line, it could be as simple as:

xargs -n1 func < file

or more complicated using:

cat file | xargs -n1 -I{} func {}
查看更多
登录 后发表回答