1

I have a variable called "num", that holds a number. I want to use it in "sed" like so:

sed '1,$(num)d' file.txt

also tried:

sed '1,($num)d' file.txt

...so that I can delete lines from 1 until the line num.

It gives me an error like this:

sed: -e expression #1, char 4: unknown command: `('

What is the correct way to do this? thank.

makansij
  • 9,303
  • 37
  • 105
  • 183

2 Answers2

3

Your shell variable usage was incorrect. First, using the double quote ensures that the shell will expand the variable. Second, surrounding the variable in question (num) with the braces ensures that the variable will be seen by the shell as $num, instead of the subsequent d getting glommed on.

Here is how you should specify what you want to do:

sed "1,${num}d" file.txt

Ram Rajamony
  • 1,717
  • 15
  • 17
  • I thought of that, but I thought that the double quotes `""` don't expand the `{}`, because they only expand slashes, backticks, and dollar signs. I guess they also expand `{}`? – makansij Sep 15 '15 at 19:46
  • 1
    Surrounding a variable name with braces is how the shell disambiguates the characters making up a variable from any trailing characters that should not be a part of the variable name – Ram Rajamony Sep 15 '15 at 19:48
2

You can use single quotes but need to concatenate the script

num=42; seq 1 45 | sed '1,'$num'd'

will print

43
44
45

as expected.

karakfa
  • 66,216
  • 7
  • 41
  • 56