Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Linux shell how can I process each line of a multiline string?

Tags:

linux

shell

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?

like image 573
yazz.com Avatar asked Feb 19 '11 15:02

yazz.com


People also ask

How do you execute a multi-line command in shell?

The (&&) and (;) can execute a multi-line code that runs commands that are dependent and then independent of previous statements. A subshell can include commands listed within curly braces or the EOF tag. Curly braces could include a subshell and/or EOF tag. The EOF tag can include subshells and curly braces.

How do you echo multiple lines in shell?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

How do you echo a multiline string?

Use echo With the -e Option to Make Multi-Line String in Bash. The following bash script prints the words to multiline. txt without any extra spaces. The -e option enables the interpretation of escape characters in the variable greet .


1 Answers

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.

like image 106
osgx Avatar answered Sep 20 '22 12:09

osgx