Home > How & Why, Interactive knowledge & Tips n Tricks & other reference stuff > AWK: How to remove all spaces & tabs from all fields of a file

AWK: How to remove all spaces & tabs from all fields of a file

August 1st, 2010 670 views Leave a comment Go to comments

Following command will help you to remove all trailing and leading spaces from all fields of a text file. It also remove tab characters. I am assuming that all the fields in input file are separated by “^”. If you are using any other separator then set the value of FS in BEGIN block accordingly.

 awk 'BEGIN {FS="^";OFS="^";}{for (i=1; i<=NF; i++) {gsub(/^[ \t]+|[ \t]+$/,"",$i);} print }' filename > file_name_new
Please note this
This example will also help you to build data file for you database where you need to insert blank or null value when value for a field does not exist.
Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

  1. No comments yet.