brad
brad

Reputation: 1023

sed or awk to match part of strings

I have looked through SO and found many things similar, but this is less complicated I just cant seem to quite get there... I am working on csv text manipulation to automate tasks. I need to replace Communication, with Communication - articulating one's self; but when the string Sports Communication, appears I dont want that changed. I think its close to

sed -i.bak "s/[Sports]! Communication,/Communication - articulating one\'s self;/g" out.csv 

I would be fine with an awk solution but more familiar with sed its in a bash file so really any common command line solution would be great

unassigned,2.5,"Sports Communication,","The Campus...lots of other data...will be required.",Communication,Collaboration,Brand

Communication can be switched with Collaboration or Brand or not be there

Upvotes: 1

Views: 125

Answers (2)

Inian
Inian

Reputation: 85693

You can use Awk statement like this,

awk -F\, '{for(i=1;i<=NF;i++) { if(match($i,/^Communication$/)) {gsub(/^Communication$/,"Communication - articulating one\047s self;",$i);} }}1' file

which produces an output as below for your input file

unassigned 2.5 "Sports Communication " "The Campus...lots of other data...will be required." Communication - articulating one's self; Collaboration Brand

In latest GNU Awk (since 4.1.0 released), it has the option of "inplace" file editing:

[...] The "inplace" extension, built using the new facility, can be used to simulate the GNU "sed -i" feature. [...]

and to keep a backup of the file with an extension a needed

gawk -i inplace -v INPLACE_SUFFIX=.bak -F\, '{for(i=1;i<=NF;i++) { if(match($i,/^Communication$/)) {gsub(/^Communication$/,"Communication - articulating one\047s self;",$i);} }}1' file

(or) for an older version, just use a temporary file and swap it back,

awk -F\, '{for(i=1;i<=NF;i++) { if(match($i,/^Communication$/)) {gsub(/^Communication$/,"Communication - articulating one\047s self;",$i);} }}1' file > temp && mv temp > file

One-level of simplification based on the one-and-the-only Ed Morton's comments below to directly do the substitution and avoid an un-necessary match(),

awk -F\, '{for(i=1;i<=NF;i++) {sub(/^Communication$/,"Communication - articulating one\047s self;",$i);} }1' file

Upvotes: 3

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

sed approach:

sed "s/\(,Communication\),/\1 - articulating one's self;,/g" file

awk approach:

awk -F',' '{for(i=1;i<=NF;i++){ if($i~/^Communication/)
    {gsub("Communication","Communication - articulating one\047s self;",$i);} }}1' file

Upvotes: 1

Related Questions