0

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.

3
  • 1
    Can you expand the "with no luck" sentence? What was your output? Commented Jan 14, 2015 at 8:43
  • by no luck I mean that the output was the same as the input. But A.M.D.'s answer seems to have solved my problem! Commented Jan 14, 2015 at 8:44
  • Well the problem lies in the -v FS=OFS=";" expression, the gsub() part is fine. You cannot set two variables in the same expression, so you needed -v FS=";" -v OFS=";". Commented Jan 14, 2015 at 8:47

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, that was fast! Your answer seems to work, I'm gonna test it now on some files. Thanks!
i'll wait for your results :-)
Aaaaand..... the results are in! It works like a charm. Although the other solutions metioned in this thread also work, I'll mark yours as you're the first ;-) Thanks!
1

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

Comments

1

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

1 Comment

'gsub(/ /,"",$3)+gsub(/ /,"",$4)+7' is one character briefer than '{gsub(/ /,"",$3);gsub(/ /,"",$4)}7'. Not sure it's worth the tradeoff in clarity or the time it took me thinking about it to convince myself it'd always succeed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.