Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

where x would be the variable, but that simply prints out all lines instead of just a single one (say line 1 for instance). How could I go about adapting this to print out a specific line instead of all of them? (would like to avoid having to write the variable to a file instead)

like image 368
lacrosse1991 Avatar asked Apr 03 '13 01:04

lacrosse1991


1 Answers

To print the Nth line:

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

or (more portably):

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

or

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

or

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

or (for the 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
like image 152
William Pursell Avatar answered Oct 07 '22 14:10

William Pursell