June 22, 2011
Using Awk to Limit Output by Character Count
Sometimes you need to print a specific amount of characters from each line output. This can seem like a challenge, but if you know a little awk magic it’s actually not that bad. Below is an easy example of how to output a set amount of characters per line via bash and awk.
Print the first 3 characters of output:
echo 1234567890 | awk '{print substr( $0, 0, 3 )}'
The output should be ‘123’.
Print the last 3 characters of output:
echo 1234567890 | awk '{print substr( $0, length($0) - 2, length($0) )}'
The output should be ‘890’.
Easy as pie!