Tuesday, 21 February 2017

Linux Command

1. Delete last 23 lines from a file in unix.

Use sed, but let the shell do the math, with the goal being to use the d command by giving a range (to remove the last 23 lines):
sed -i "$(($(wc -l < file)-22)),\$d" file
To remove the last 3 lines, from inside out:
$(wc -l < file)
Gives the number of lines of the file: say 2196
We want to remove the last 23 lines, so for left side or range:
$((2196-22))
Gives: 2714 Thus the original sed after shell interpretation is:
sed -i 2174,$d file
With -i doing inplace edit, file is now 2173 lines!

OR
   awk '{buf[NR-1]=$0;}END{ for ( i=0; i < (NR-23); i++){ print buf[i];} }'

No comments:

Post a Comment