Tuesday, May 27, 2008

Print last 2 characters using awk substr


I have already discussed about awk substr function in one of my previous post.
Now using that I have to extract the last two characters of each line from details.out


$ cat details.out
200KG
2567.89KG
132.3MG
1200MG
Id250d hn


i.e. output required:


KG
KG
MG
MG
hn


Using awk:

$ awk '{ print substr( $0, length($0) - 1, length($0) ) }' details.out


Using sed:

$ sed 's/^.*\(..\)$/\1/' details.out


Similar Post:

- removing last two characters from the above file.

8 comments:

Anonymous said...

The analog bash substring expansion solution:

while read line; do echo ${line: -2}; done <<< "$(<file)"

The space between line: and -2 is mandatory, otherwise bash confuses it with the default value for the 'line' variable.

Fredri said...

I think the following is best for readability and conciseness.

rev details.out | cut -b-2 | rev

Of course very inefficient, but if efficiency was an issue you would just use C over bash.

Dana B said...

Hi, thanks for the info. I needed to grab the last 4 characters of a string so I modified your code and created a script file.

#! /bin/bash
# Purpose: Return the ordinal permissions of a Unix/Mac/Linux file.
# Notes…: The stat command will return six digits and we only want the last four so the stat output
# is passed to awk to get only the last four characters
# Example: 100777 becomes 0777 after awk parses
stat -f "%p" $1 | awk '{ print substr( $0, length($0) - 3, length($0) ) }'

Unknown said...

@Dana B
Thanks for sharing this.

Unknown said...

@Fredri True, thanks for sharing the command.

Unknown said...

@kon thanks for the hint.

Unknown said...

Various ways to extract the last 2 characters:

rev yourfile | cut -c-2 | rev

while IFS= read -r line; do expr "x$line" : 'x.*\(..\)' \| "$line"; done < yourfile

perl -ple '$_ = substr($_,-2)' yourfile

perl -ple '$_ = scalar reverse unpack "A2", scalar reverse' yourfile

perl -lne 'print /(..?)$/' yourfile

sed -e '/.../s/..$/\n&/;/\n/D' yourfile

Unknown said...

Various ways to extract the last 2 characters:

rev yourfile | cut -c-2 | rev

while IFS= read -r line; do expr "x$line" : 'x.*\(..\)' \| "$line"; done < yourfile

perl -ple '$_ = substr($_,-2)' yourfile

perl -ple '$_ = scalar reverse unpack "A2", scalar reverse' yourfile

perl -lne 'print /(..?)$/' yourfile

sed -e '/.../s/..$/\n&/;/\n/D' yourfile

© Jadu Saikia www.UNIXCL.com