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?
Removing the last n characters To remove the string's last n characters, we can use the built-in substring() function in R.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With