Delete lines from a file

Friday, December 28, 2012 0 Comments


->deleting all rows except the first from a file
->deleting a row from file with a line number
->deleting rows from a file with a range of line numbers

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

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 btwn lines $a,$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

0 comments: