Is there a cleaner way of getting the last N characters of every line?

merlin2011 picture merlin2011 · Jun 26, 2014 · Viewed 27.2k times · Source

To simplify the discussion, let N = 3.

My current approach to extracting the last three characters of every line in a file or stream is to use sed to capture the last three characters in a group and replace the entire line with that group.

sed 's/^.*\(.\{3\}\)/\1/'

It works but it seems excessively verbose, especially when we compare to a method for getting the first three characters in a line.

cut -c -3

Is there a cleaner way to extract the last N characters in every line?

Answer

Tiago Lopo picture Tiago Lopo · Jun 26, 2014

It's very simple with grep -o '...$':

cat /etc/passwd  | grep -o '...$'
ash
/sh
/sh
/sh
ync
/sh
/sh
/sh

Or better yer:

N=3; grep -o ".\{$N\}$" </etc/passwd
ash
/sh
/sh
/sh
ync
/sh
/sh

That way you can adjust your N for whatever value you like.