I want to sed using a variable.

For example, sed -n '1,10p' file. So, instead of 10, I want to use $k where k is an integer.



sed cannot expand shell or environment variables. Rather you have to select quotes that allows the shell, Bash, to do the expansion. When they're enclosed in double quotes, Bash will expand variables within, but not when they're enclosed in single quotes. To use single quotes you'd need to do something like this:

$ sed -n '1,'$k'p' file

NOTICE: In the above that we've exposed the variable, $k so that it's not inside either of the quotes of the arguments being passed into sed. By doing this the shell, Bash, will expand $k to whatever value it's set to.

If you use double quotes you can use the ${var} notation to guard the variable within double quotes so that the shell will expand it. Below the ${k} notation is required because otherwise the variable name $k would be followed by the p thus leading the Bash shell into thinking the variable's name is $kp.

$ sed -n "1,${k}p" file

You could also do the above by putting a space in between the variable, $k and the p. This works because sed syntax allows whitespace between an address and a command (in other words, the space is passed to sed with this form, unlike with ${k}).

$ sed -n "1,$k p" file

NOTE: You need to use some caution with these methods, since they'll fail if $k is unset:

$ printf "blah %d\n" $(seq 10) |  sed -n '1,'$k'p'
sed: -e expression #1, char 3: unexpected `,'


Here's the double quoted ${k} variant as an example:

$ k="3"; printf "blah %d\n" $(seq 10) |  sed -n "1,${k}p"
blah 1
blah 2
blah 3

shell vs. environment variables

For more on this topic, I highly encourage you to read this U&L Q&A titled: What is the difference in usage between shell variables and environment variables?.



Try this,

  sed -n '1,'$k'p' file

Inside a single quote, everything is preserved literally, without exception.

So we can negate that by adding single quotes around the variable.

  • 3
    that $k is unquoted, so all the issues related to using unquoted variables would come into play in this commandline. – Rakesh Sharma Aug 16 '18 at 2:23

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