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

I have a command that prints multiple lines, and I want to put the second line in a bash variable.

like echo "AAA\nBBB" , and I need a bash command that puts the BBB in a bash variable.

+7
source share
7 answers

With sed :

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

With awk :

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

Then just repeat your variable:

 echo "$var" 
+12
source

Call read twice:

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

Note that you need {} , so make sure that both commands receive the same input stream. In addition, variables are not available outside of {} , so this does not work:

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

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.

+2
source

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

+1
source

Use an array with a parameter extension to avoid subnets:

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

Like this:

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

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

0
source

All Articles