I am using this command with variables

sed '/${LN_NM}/d' file.txt

I am using it to delete a line from file.txt. But when this command is used without the variable it works fine.

  • 4
    Variables are not expanded in single quotes, use double quotes.
    – pLumo
    Mar 25, 2020 at 8:31
  • 2
    Apart from using double quotes you also need to do away with the slashes. Mar 25, 2020 at 9:09

2 Answers 2


/regular expression/d will delete lines that match that regular expression (So if $LN_NUM is just a number like 5 or 18, every line with that number somewhere in it). If you want to instead delete the given line number:

sed "${LN_NM}d" file.txt

If you want to save the file after deleting that line from it, use ed, not sed:

ed -s file.txt <<EOF
  • You can use sed -i to edit the file in place, instead of using ed. Mar 25, 2020 at 20:09
  • 1
    @DavidConrad I can't recommend that; sed -i is non standard and different implementations that support it as an extension have different behaviors - OS X sed, for example, requires it to have an argument, while one is optional with GNU sed. Better to stay within POSIX especially when the asker doesn't say what OS they're using.
    – Shawn
    Mar 25, 2020 at 20:22
  • Fair enough. I upvoted you. Cheers. Mar 25, 2020 at 20:51

As @plumo already mentioned, variables wont get substituted while using ' (single quotes)

Change your command by using " double-quotes, which should do the trick.

sed "/${LN_NM}d/" file.txt

  • 1
    That will delete lines containing the number in $LN_NUM, not the exact line number...
    – Shawn
    Mar 25, 2020 at 16:57
  • sorry, I misstyped the regular expression. I've updated the answer to correct it. Mar 26, 2020 at 11:40
  • Uh, no. That won't even delete lines matching the regular expression, much less the line with the specific line number. Try it before you post. Mar 26, 2020 at 18:22

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.