How to delete a line by passing line number as var

2020-04-05 07:11发布

问题:

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?

回答1:

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

Using 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

Using 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


标签: bash shell