Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I read the second line of the output of a command into a bash variable?

Tags:

bash

I have a command that prints several lines and I do want to put the second line into a bash variable.

like echo "AAA\nBBB" and I want a bash command that would put BBB in a bash variable.

like image 562
sorin Avatar asked Nov 29 '12 11:11

sorin


People also ask

How do I read a line in bash?

Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.

How do I print a second line in Linux?

head -2 creates a file of two lines. tail -1 prints out the last line in the file.

How do I print the next line in a bash script?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.


2 Answers

With sed:

var=$(echo -e "AAA\nBBB" | sed -n '2p')

With awk:

var=$(echo -e "AAA\nBBB" | awk 'NR==2')

Then simply, echo your variable:

echo "$var"
like image 67
Steve Avatar answered Oct 03 '22 11:10

Steve


Call read twice:

echo -e "AAA\nBBB" | { read line1 ; read line2 ; echo "$line2" ; }

Note that you need the {} so make sure both commands get the same input stream. Also, the variables aren't accessible outside the {}, so this does not work:

echo -e "AAA\nBBB" | { read line1 ; read line2 ; } ; echo "$line2"
like image 25
Aaron Digulla Avatar answered Oct 03 '22 11:10

Aaron Digulla