user8341893
user8341893

Reputation: 1

find a string and update 4th field in unix

I am trying to find a string and update 4th filed in a | seperated file in Unix.I have below sample file.

ROSE.2017|D|5:00 AM||||
YELLOW.2017|D|5:00 AM||||
BLUE.2017|D|5:00 AM||||

Search the string YELLOW.2017 and if find then update corresponding line 4th field with YES I want below result.

ROSE.2017|D|5:00 AM||||
YELLOW.2017|D|5:00 AM|YES|||
BLUE.2017|D|5:00 AM||||

I am using below command and getting below wrong result.

nawk -F'|' '$1=="'$fname'"{$4="YES"}1' filename.txt > filename1.txt

where fname=YELLOW.2017

wrong result:

ROSE.2017|D|5:00 AM||||
YELLOW.2017 D 5:00 AM YES
BLUE.2017|D|5:00 AM||||

My Unix version is SunOS 5.10

Upvotes: 0

Views: 50

Answers (1)

James Brown
James Brown

Reputation: 37414

If you edit a record, it gets rebuilt and field separators get updated with output field separator (OFS) so you need to set that also.

Another way to get the value of $fname to your script is to set an awk variable to its value (-v fname="$fname"):

$ fname="YELLOW.2017"
$ awk -v fname="$fname" 'BEGIN{FS=OFS="|"} $1==fname{$4="YES"}1' file
ROSE.2017|D|5:00 AM||||
YELLOW.2017|D|5:00 AM|YES|||
BLUE.2017|D|5:00 AM||||

Upvotes: 1

Related Questions