UnixTips.net

* use my tips at your own risk !!

* use my tips at your own risk !!

Categories

  • Other (3)
  • Scripting (10)
  • Unix (70)
  • Wordpress (2)

Powered by Genesis

awk substitution using gsub

Handy gsub examples:

Removing the trailing % in the 5th field.

# echo "1 2 3 4 85%" | awk '/%/{gsub( /%/," ",$5); print}'
1 2 3 4 85
  • /%/ operate only on lines with a %
    (this means empty lines are skipped)
  • gsub(a,b,c) match the regular expression a, replace it with b,
    and do all this with the contents of c
  • print print the contents of the entire line
# echo "1 2 3 4 85%" | awk '/%/{gsub( /%/," ",$5); print $5}'
85
  • /%/ operate only on lines with a %
    (this means empty lines are skipped)
  • gsub(a,b,c) match the regular expression a, replace it with b,
    and do all this with the contents of c
  • print $5 print the contents of the 5th field
# echo "1 2 3 4 85%" | awk '/%/{gsub( /%/," ",$5); print $5","$2}'
85 ,2
  • /%/ operate only on lines with a %
    (this means empty lines are skipped)
  • gsub(a,b,c) match the regular expression a, replace it with b,
    and do all this with the contents of c
  • print $5″,”$2 print the contents of field 5, a comma, then field 2
# echo "1:2:3:4:85%" |  awk -F: '/%/{gsub( /%/," ",$5); print$5","$2}'
85 ,2
  • -F: use : as field separator
  • /%/ operate only on lines with a %
    (this means empty lines are skipped)
  • gsub(a,b,c) match the regular expression a, replace it with b,
    and do all this with the contents of c
  • print$5″,”$2 print the contents of field 5, a comma, then field 2

Need to remove white spaces?

# echo "1: 2 :3:4:5:6" | awk -F: '{print $2}'
 2 
# echo "1: 2 :3:4:5:6" | awk 'BEGIN{FS=OFS=":"}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1'
1:2:3:4:5:6
  • BEGIN{FS=OFS=”:”} – use : as field separator
  • gsub(/^[ \t]+/,””,$2); – starting at the beginning (^) replace all (+ = zero or more, greedy)
    consecutive tabs and spaces with an empty string
  • gsub(/[ \t]+$/,””,$2)} – do the same, but now for all space up to the end of string ($)
    1 – =”true”. Shorthand for “use default action”, which is print $0
    – that is, print the entire (modified) line
# echo "1: 2 :3:4:5:6" | awk 'BEGIN{FS=OFS=":"}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2); print $2}'
2

Same as above but print specific fields.

  • ;print $2 print the 2nd field. Notice the print is before the curly bracket } and followed by a semi-colon :

This post was based on the following stockoverflow.com question:
http://stackoverflow.com/questions/20600982/remove-leading-and-trailing-space-in-field-in-awk