Ive seen many variations, very confused on how to solve these 3 problems.
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.
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.
There is no available to delete all contents of the file. How to delete all contents of the file using sed command.
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.
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
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.
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