If your variable contains only digit, what you have done is correct:
sed "$lnum!d" cloud.cpp
For passing shell variable to sed
in general, please read this answer.
Now, you have done it correctly in this case, but it still doesn't work. It dues to your shell, which probably bash
, zsh
or csh
. Those shells support history expansion, which is denoted by !
(This feature is original from csh
and copied later by bash
and zsh
).
In bash
, zsh
, history expansion is enabled by default in interactive session, and will be performed inside double quotes.
In zsh
:
$ seq 10 | sed "10!d" # <-- press enter
$ seq 10 | sed "10dash"
as dash
is my latest command in history start with d
.
In bash
:
$ seq 10 | sed "10!d"
bash: !d": event not found
as I don't have any command in bash history start with d
.
You can turn off history expansion:
set +H
or:
set +o histexpand
in bash
and:
set -K
or:
setopt nohistexpand
in zsh
.
For more portable way, without relying on your shell options, you can always do:
sed "$lnum"\!d cloud.cpp
which causes your shell treating !
literally.