'Delete lines from file with SED or AWK
Ive seen many variations, very confused on how to solve these 3 problems.
- 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
Solution 1:[1]
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.
Solution 2:[2]
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
Solution 3:[3]
you can just use bash if your system has it. The basic idea behind is to set a count and incrementing this count while iterating the file.
1) deleting all rows except the first from a file
read -r line < file; echo "$line" > temp && mv temp file
2) deleting a row from file with a line number
declare -i count=0
while read -r line
do
((count++))
case "$count" in
10) continue;;
* ) echo "$line";;
esac
done < file > temp && mv temp file
3) deleting rows from a file with a range of line numbers eg from 10 to 20
declare -i count=0
while read -r line
do
((count++))
if (( $c < 10 && $c > 20 ));then
echo "$line";;
fi
done < file > temp && mv temp file
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anubhava |
| Solution 2 | |
| Solution 3 | bash-o-logist |
