108

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?

0

4 Answers 4

159

Use command substitution like this:

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

This also hangs....I'm starting to think that I don't fully understand the issue I'm having.
Are you using the exact command that I said?
of course....I did an update and now it works. Thank you all very much
35

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

2 Comments

I've tried this...it isn't working line = sed -n '2p' myfile just hangs...
the second way worked for me, thank you @KarolyHorvath :)
8

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

Comments

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

1 Comment

I've fixed the formatting of your answer.