How to delete line 7 in a file in Bash with sed?

How to delete line 7 in a file in Bash?

I tried

$ sed -i '7d' ~/demo
error:sed: 1: "~/demo": command a expects \ followed by text

Solution 1:

From man sed:

SYNOPSIS
     sed [-Ealnru] command [-I extension] [-i extension] [file ...]

So if you use -i you also need to specify an extension for the backup file. If you don't want a backup file to be created but still edit in-file, use ''.

sed -i '' '7d' ~/demo

To take the number of the line to be deleted from a variable, use

DELETE_LINE=7
sed -i '' "${DELETE_LINE?}d" ~/demo

$(VAR?} makes the shell throw an error if the variable isn't set. This avoid running the command without a line number (which would delete all lines).

PS: Interestingly enough, sed '7d' -i '' ~/demo does not work (even though the synopsis implies it should). sed -e '1d' -i '' ~/demo does though.