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+awksolution, could you please try following. Just setlinevariable ofawkto line(from bottom) whichever you want to skip.Explanation: Using
tacwill read the Input_file reverse(from bottom line to first line), passing its output toawkcommand 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+wcsolution, kindly try following.Explanation: Starting
awkprogram here and creating a variablelineswhich has total number of lines present in Input_file in it. variableskipLinehas 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+1then printing the lines.3rd solution: Adding solution as per Ed sir's comment here.
Explanation: Adding detailed explanation for 3rd solution.