Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete lines from file with SED or AWK

Ive seen many variations, very confused on how to solve these 3 problems.

  1. deleting all rows except the first from a file
  2. deleting a row from file with a line number
  3. deleting rows from a file with a range of line numbers
like image 553
bluetickk Avatar asked Apr 19 '11 19:04

bluetickk


People also ask

How do you delete a line in a file with 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 a specific line from a file in Unix?

To Remove the lines from the source file itself, use the -i option with sed command. If you dont wish to delete the lines from the original source file you can redirect the output of the sed command to another file.

Can we delete content in a file by using sed command?

There is no available to delete all contents of the file. How to delete all contents of the file using sed command.

How do I delete an awk record?

To delete line 1, use awk 'NR!= 1'. The default action is to print the line. All of your '{next} {print}' terms can be removed.


Video Answer


2 Answers

With awk:

# delete line 1
awk 'NR == 1 {next} {print}' file

# delete line number stored in shell variable $n
awk -v n=$n 'NR == n {next} {print}' file

# delete between lines $a and $b inclusive
awk -v m=$a -v n=$b 'm <= NR && NR <= n {next} {print}' file

To save a few chars, {print} can be replaced just with 1

To overwrite the original file, you have to do something like this

awk '...' file > tmpfile && mv tmpfile file
like image 22
glenn jackman Avatar answered Sep 20 '22 00:09

glenn jackman


Using sed:

Delete 1st line:

sed '1d' file-name

Delete 10th line:

sed '10d' file-name

Delete line # 5 to 10

sed '5,10d' file-name

All above sed commands will write output on stdout that you can redirect to another file if you want or use -i flag of sed to inline edit the file.

like image 74
anubhava Avatar answered Sep 23 '22 00:09

anubhava