I have several text files with different row numbers and I have to delete in all of them the third-to-last line . Here is a sample file:
bear
horse
window
potato
berry
cup
Expected result for this file:
bear
horse
window
berry
cup
Can we delete the third-to-last line of a file:
a. not based on any string/pattern.
b. based only on a condition that it has to be the third-to-last line
I have problem on how to index my files beginning from the last line. I have tried this from another SO question for the second-to-last line:
> sed -i 'N;$!P;D' output1.txt
With
tac
+awk
solution, could you please try following. Just setline
variable ofawk
to line(from bottom) whichever you want to skip.Explanation: Using
tac
will read the Input_file reverse(from bottom line to first line), passing its output toawk
command and then checking condition if line is equal to line(which we want to skip) then don't print that line, 1 will print other lines.2nd solution: With
awk
+wc
solution, kindly try following.Explanation: Starting
awk
program here and creating a variablelines
which has total number of lines present in Input_file in it. variableskipLine
has that line number which we want to skip from bottom of Input_file. Then in main program checking condition if current line is NOT equal tolines-skipLine+1
then printing the lines.3rd solution: Adding solution as per Ed sir's comment here.
Explanation: Adding detailed explanation for 3rd solution.