101

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?

Benjamin W.
  • 38,596
  • 16
  • 96
  • 104

4 Answers4

149

Use command substitution like this:

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

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

dogbane
  • 254,755
  • 72
  • 386
  • 405
31

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 ....

Jakob Weisblat
  • 6,970
  • 9
  • 36
  • 63
Karoly Horvath
  • 91,854
  • 11
  • 113
  • 173
5

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

Community
  • 1
  • 1
tamajit
  • 51
  • 1
  • 1
-1
line=`sed -n 2p myfile`
echo $line
devnull
  • 111,086
  • 29
  • 224
  • 214
Adam
  • 11