I have a CSV file in which every column contains unnecessary extra spaces added to it before the actual value. I want to create a new CSV file by removing all the spaces.
For example
One line in input CSV file
123, ste hen, 456, out put
Expected output CSV file
123,ste hen,456,out put
I tried using awk to trim each column but it didn't work.
awk
is your friend.Input
Script
Output
Note
/^$/{next}
.or written out loud:
Run with:
This sed should work:
This will remove leading spaes, trailing spaces and spaces around comma.
Update: Here is an awk command to do the same:
Another way to do with
awk
to remove multiple leading white-spaces is as below:-FS=OFS=","
sets the input and output field separator to,
s = ""; for (i = 1; i <= NF; i++)
loops across each column entry up to the end (i.e. from$1
,$2
...NF
) and thegsub(/^[ \t]+/,"",$i)
trims only the leading white-space and not anywhere else (one ore more white-space, note the+
) from each column.If you are want to do this action for an entire file, suggest using a simple script like below
You could try :
cat ~/path/file.csv | tr -d "\ " sed "s/, /,/g" ~/path/file.csv
To remove leading blank chars with sed:
With GNU awk:
With other awks:
To remove blank chars before and after the values with sed:
With GNU awk:
With other awks:
Change
(a single blank char) to
[[:blank:]]
if you can have tabs as well as blank chars.