sorin
sorin

Reputation: 170478

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

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.

Upvotes: 17

Views: 21305

Answers (7)

koola
koola

Reputation: 1734

Use an array with parameter expansion to avoid subshells:

str="AAA\nBBB"
arr=(${str//\\n/ })
var="${arr[1]}"
echo -e "$str"

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328614

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"

Upvotes: 7

Chris Seymour
Chris Seymour

Reputation: 85795

Like this:

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

Upvotes: 0

Tyzoid
Tyzoid

Reputation: 1078

in a bash script: Variable=echo "AAA\nBBB" | awk "NR==2"

Upvotes: 0

Steve
Steve

Reputation: 54402

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"

Upvotes: 24

P.P
P.P

Reputation: 121397

You can use sed:

SecondLine=$(Your_command |sed -n 2p)

For example:

 echo -e "AAA\nBBBB" | sed -n 2p

You change the number according to the line you want to print.

Upvotes: 3

Lars Kotthoff
Lars Kotthoff

Reputation: 109232

You can do this by piping the output through head/tail -- var=$(cmd | tail -n +2 | head -n 1)

Upvotes: 1

Related Questions