1

I find the following way to print line from file

In this example we want to print the first line from the hosts file

sed -n '1,1p'  /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4

But how to do the same with parameters inside the sed command

For example

Line_number=1
sed -n ' $Line_number,$Line_numberp'  /etc/hosts
 sed: -e expression #1, char 4: extra characters after command

what is wrong in my sed syntax?

migrated from serverfault.com Jul 10 '14 at 8:49

This question came from our site for system and network administrators.

1

Let your shell expand the variable by using " instead of '.

Example:

victor@pyfg:~$ line_number=2
victor@pyfg:~$ sed -n "${line_number},${line_number}p" /etc/hosts
1.2.3.4 row-2

Since you're only printing a single row, you can just to it like this also:

victor@pyfg:~$ sed -n "${line_number}p" /etc/hosts
1.2.3.4 row-2
0

just for fun, an awk solution:

awk -v line=2 'FNR==line' /etc/hosts
0

It's probably best in your example case to have sed quit the input file once you've found printed the data you desire. For instance:

sed 1q <INPUT

That will autoprint the first line and then end the process altogether. You can also do:

head -n1 <INPUT

...to achieve the same effect.

sed also interprets address,ranges though, and these can be /regex/,/addresses/ or combinations of the two types as well. For instance:

sed '9q;/LINE[0-9]/,/^$/!d' <<FILE
$(printf 'LINE %s\nLINE%s\nLINE %s\\nNOT LINE %s\n\n' $(seq 32))
FILE

###OUTPUT###

LINE2
LINE 3\nNOT LINE 4

LINE6
LINE 7\nNOT LINE 8

LINE 9

In the above example sed deletes any line it encounters that does !not occur between a line containing the string LINE immediately followed by [0-9] - or any numeric character - and a line not containing /^$/ any characters at all - or a blank line. In this way lines 1 and 5 - orLINE [15] are removed from its output. Conversely though, LINE 9 is printed because it is instructed to q on 9 so it stops processing its script at that point - which occurs before the filter that would delete it.

As suggested in another answer, handling variable parameters is as simply done as allowing the shell to expand them for you - so you should use "$parameter" in order to do so. It is important to remember though that invalid input will be treated as such. For example, for the same reason:

echo "///" | sed 's////g'     
sed: -e expression #1, char 5: unknown option to `s'

...neither does:

v=/ ;echo "///" | sed "s/$v//g"                                 :(
sed: -e expression #1, char 5: unknown option to `s'

The value of each variable must be valid sed script and cannot contain its delimiter characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.