Store output of sed into a variable

Bash

Bash Problem Overview


I want to store the second line of my file into a variable, so I am doing this:

sed -n '2p' myfile

I wish to store the output of the sed command into a variable named line.

What is the correct syntax to do this?

Bash Solutions


Solution 1 - Bash

Use command substitution like this:

line=$(sed -n '2p' myfile)
echo "$line"

Also note that there is no space around the = sign.

Solution 2 - Bash

In general,

variable=$(command)

or

variable=`command`

The latter one is the old syntax, prefer $(command).

Note: variable = .... means execute the command variable with the first argument =, the second ....

Solution 3 - Bash

To store the third line into a variable, use below syntax:

variable=`echo "$1" | sed '3q;d' urfile`

To store the changed line into a variable, use below syntax: variable=echo 'overflow' | sed -e "s/over/"OVER"/g" output:OVERflow

Solution 4 - Bash

line=`sed -n 2p myfile`
echo $line

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser583507View Question on Stackoverflow
Solution 1 - BashdogbaneView Answer on Stackoverflow
Solution 2 - BashKaroly HorvathView Answer on Stackoverflow
Solution 3 - BashtamajitView Answer on Stackoverflow
Solution 4 - BashAdamView Answer on Stackoverflow