wtrdk
wtrdk

Reputation: 141

Removing spaces from specific column in CSV file

I have a csv file with lines like this:

300001;Company Name;023-1 2 3 4 5 6 7;023-3 2 4 6 43 4;[email protected];;;;Street Name;184;;Postal Code;City

I want to strip the spaces from column 3 and 4 (phone and fax number)so that it looks like this:

300001;Company Name;023-1234567;023-3246434;[email protected];;;;Street Name;184;;Postal Code;City

I tried these awk-codes (for column 3) I found on Stackoverflow with no luck:

awk -v FS=OFS=";" '{gsub(/ /,"",$3)} 1' file.csv > test.csv
awk -F, '$3 ~ / / { OFS= ";"; $3 = ""; } 1' file.csv > test.csv

I've been googling for half a day now, but can't find anything that works.

Upvotes: 0

Views: 2000

Answers (3)

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5308

Try this:

awk 'BEGIN{FS=OFS=";"} {gsub(/ /,"",$3); gsub(/ /,"",$4)}1' File

We set the input and output field seperators as ;. Then substitute the spaces in the 3rd and 4th fields with nothing. Hope it helps.

As others have already mentioned, setting both FS and OFS at one shot (FS=OFS=";") with -v is the reason why it didn't work in your case. I moved the same to BEGIN block. Thats it.

Upvotes: 1

Kent
Kent

Reputation: 195239

your cause of problem is -v FS=OFS=";" you can either use:

awk -F';' -v OFS=";" '...'

or

awk 'BEGIN{FS=OFS=";"} ...'

Other codes look ok, except that you forgot the column4. this line should work:

awk -F';' -v OFS=";" 'gsub(/ /,"",$3)+gsub(/ /,"",$4)+7' file

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26677

The issue is that you cannot set FS and OFS in one go. Seperate the two as

$ awk  -vFS=";" -vOFS=";" '{gsub(" ","",$3); gsub(" ", "", $4) }1' input
300001;Company Name;023-1234567;023-3246434;[email protected];;;;Street Name;184;;Postal Code;City

Upvotes: 1

Related Questions