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.
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.
head -2 creates a file of two lines. tail -1 prints out the last line in the file.
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.
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With