I want to delete a line of a document by passing the number as variable, like so:
ERR=`set of bash commands` ; sed '${ERR}d' file
However the above sed command in single quotes does not work. How to achieve this task then?
Deleting line using sed To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.
The syntax is <address><command> ; where <address> can be either a single line like 5 or a range of lines like 5,10 , and the command d deletes the given line or lines. The addresses can also be regular expressions, or the dollar sign $ indicating the last line of the file.
For a given file like
$ cat file
1
2
3
4
5
6
7
8
9
10
and your variable containing the line number like
$ ERR=5
sed
:Use double quote to allow the variable to interpolate. Notice the use of curly braces to allow sed
to differentiate between variable and d
flag. In the output line number 5 is no longer printer.
$ sed "${ERR}d" file
1
2
3
4
6
7
8
9
10
awk
:NR
stores the line number for a given file. Passing the shell variable to awk
using -v
option we create an awk
variable called no
. Using the condition where NR
is not equal to our awk
variable we tell awk
to print everything except the line number we don't want to print.
$ awk -v no="$ERR" 'NR!=no' file
1
2
3
4
6
7
8
9
10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With