Nolohice
Nolohice

Reputation: 339

adding a pattern to the end of each column

Say I have a file similar to this format :

"pop","hand stuff","test "
"non","no way","good "

except except of having only 3 columns it has hundreds. I want to add @ at the end of each column so the output is

"pop@","hand stuff@","test @"
"non@","no way@","good @"

If I only had a small number of columns then I could do

awk -F"," vOFS=, '{print $1"@",$2"@",$3"@"}'

But how would I do this if I have many many columns and I don't want to have to specify each column in the awk script?

Upvotes: 0

Views: 39

Answers (3)

Ed Morton
Ed Morton

Reputation: 204456

$ sed -r 's/("[^"]+)"/\1@"/g' file
"pop@","hand stuff@","test @"
"non@","no way@","good @"

Upvotes: 1

Kevin
Kevin

Reputation: 56129

As long as your columns don't contain crazy data (specifically, \", embedded within the string), sed is easier:

OSX/BSD:

sed -E 's/"(,|$)/@"\1/g' 

GNU:

sed -r 's/"(,|$)/@"\1/g' 

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174826

You could use awk's gsub function like below.

awk '{gsub(/",/, "@\",");sub(/"$/, "@\"")}1' file

Example:

$ echo '"pop","hand stuff","test "' | awk '{gsub(/",/, "@\",");sub(/"$/, "@\"")}1'
"pop@","hand stuff@","test @"

Upvotes: 1

Related Questions