How can I echo / print specific lines from a bash variable

I am trying to print specific lines from a multi-line variable bash. I found the following:

while read line; do echo LINE: "$line"; done <<< "$x"

where x will be a variable, but it just prints all the lines instead of one (e.g. line 1). How can I adapt this to print a specific line, and not all? (I would like to avoid the need to write a variable to a file)

+5
source share
3 answers

To print the Nth line:

sed -n ${N}p <<< "$x"

or (more portable):

sed -n ${N}p << EOF
$x
EOF

or

echo "$x" | sed -n "$N"p

or

echo "$x" | sed -n ${N}p

or (for a specific case N == 3)

echo "$x" | sed -n 3p

or

while read line; do echo LINE: "$line"; done <<< "$x" | sed -n ${N}p

or

while read line; do echo LINE: "$line"; done << EOF | sed -n ${N}p
$x
EOF
+4
source

You can break it into an array like:

IFS=$'\n' lines=($x)

Then you can access any row by indexing the array, for example:

echo ${lines[1]}

(of course, lines[0]"line 1").

+7

If you don't want to use the array for any reason, and you want to do it in bash, and not by creating an external tool like this sed, you can just count the lines:

[ghoti@pc ~]$ x=$'one\ntwo\nthree\nfour\nfive\n'
[ghoti@pc ~]$ n=3
[ghoti@pc ~]$ for (( c=0; c<n; c++ )); do read line; done <<< "$x"
[ghoti@pc ~]$ echo $line
three
[ghoti@pc ~]$ 

Or using one smaller variable:

[ghoti@pc ~]$ n=2
[ghoti@pc ~]$ for (( ; n>0; n-- )); do read line; done <<< "$x"
[ghoti@pc ~]$ echo $line
two

These methods use what are sometimes called "three expressions for a loop." This is a construct that is common in many languages, from bash to awk to perl from PHP to C (but not Python!). Familiarity with them will help your programming as a whole.

Although ... you probably don't want to use bash to learn "real" programming. :-)

+2
source

All Articles