Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a line by passing line number as variable?

Tags:

bash

shell

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?

like image 677
Another.Chemist Avatar asked Apr 18 '14 04:04

Another.Chemist


People also ask

How do you delete a specific line in a file using sed?

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.

How do I remove line numbers in Linux?

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.


1 Answers

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
like image 166
jaypal singh Avatar answered Nov 12 '22 20:11

jaypal singh