How to edit the last n lines in a file

awksedtext processing

Is there a command that will allow me to edit the last n lines in a file?
I have several files, that all have a different number of lines inside. But I would like to modify the last n lines in each file. The goal is to replace commas with semicolons in the last n lines. But only in the very last n lines.

I do not want to delete any lines, I just want to replace every comma with a semicolon in the last n lines in each file.

Using the sed command I am able to replace the very last line with this command. As described here:
How can I remove text on the last line of a file?

But this only enables me to modify the very last line, and not the last n number of lines.

Best Answer

To replace commas with semicolons on the last n lines with ed:

n=3
ed -s input <<< '$-'$((n-1))$',$s/,/;/g\nwq'

Splitting that apart:

  • ed -s = run ed silently (don't report the bytes written at the end)
  • '$-' = from the end of the file ($) minus ...
  • $((n-1)) = n-1 lines ...
  • ( $' ... ' = quote the rest of the command to protect it from the shell )
  • ,$s/,/;/g = ... until the end of the file (,$), search and replace all commas with semicolons.
  • \nwq = end the previous command, then save and quit

To replace commas with semicolons on the last n lines with sed:

n=3
sed -i "$(( $(wc -l < input) - n + 1)),\$s/,/;/g" input

Breaking that apart:

  • -i = edit the file "in-place"
  • $(( ... )) = do some math:
  • $( wc -l < input) = get the number of lines in the file
  • -n + 1 = go backwards n-1 lines
  • ,\$ = from n-1 lines until the end of the file:
  • s/,/;/g = replace the commas with semicolons.