Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 954
merlin2011 Avatar asked Jun 26 '14 09:06

merlin2011


People also ask

How do you remove the last 5 characters on R?

Removing the last n characters To remove the string's last n characters, we can use the built-in substring() function in R.

How do you remove the last two characters of a shell?

To remove the last n characters of a string, we can use the parameter expansion syntax ${str::-n} in the Bash shell. -n is the number of characters we need to remove from the end of a string.

How do I remove the last 3 characters from a string in Linux?

In this method, you have to use the rev command. The rev command is used to reverse the line of string characterwise. Here, the rev command will reverse the string, and then the -c option will remove the first character. After this, the rev command will reverse the string again and you will get your output.

How do I get the last character in Linux?

To access the last character of a string, we can use the parameter expansion syntax ${string: -1} in the Bash shell. In bash the negative indices count from the end of a string, so -1 is the index of a last character.


1 Answers

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.

like image 168
Tiago Lopo Avatar answered Oct 02 '22 05:10

Tiago Lopo