Reputation: 170478
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
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
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
Reputation: 85795
Like this:
var=$(echo -e 'AAA\nBBB' | sed -n 2p)
echo $var
BBB
Upvotes: 0
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
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
Reputation: 109232
You can do this by piping the output through head/tail -- var=$(cmd | tail -n +2 | head -n 1)
Upvotes: 1