Replace a field where values are null in a file.

Hi,

I've a pipe delimited file and wanted to replace the 3rd field to 099990 where the values are null. How can I achieve it using awk or sed.

20130516|00000061|02210|111554|03710|2|205069|SM APPL $80-100 RTL|S
20130516|00000061|02210|111554|03710|2|205069|SM APPL $80-100 RTL|S
20130517|00000067||185493|03662|4|205069|SM APPL $80-100 RTL|S
20130516|00000061||111554|03710|2|205069|SM APPL $80-100 RTL|S
20130516|00000061||111554|03710|2|205069|SM APPL $80-100 RTL|S
20130517|00000067|02210|185493|03662|4|205069|SM APPL $80-100 RTL|S
awk -F"|" -v OFS="|" '!$3 { $3="099990"} 1' inputfile
1 Like

Alternatively,

awk -F"|" '$3~/^$/{$3=099990}{print}' OFS="|" input

@juzz4fun
The {print} could be replaced by 1
And $3~/^$/ is the same as !$3

awk -F\| '$3~/^$/{$3=099990}1' OFS="|"
awk -F\| '!$3{$3=099990}1' OFS="|"

another soulution (not a good one, will replace any || )

awk '{sub(/\|\|/,"|099990|")}1'

Note that 1.

!$3

also replaces fields with 0 or 00,
while 2.

$3~/^$/

only replaces empty fields.
We had a discussion in another thread about $3=="" that IMHO should be equal to 2.
But Solaris /usr/xpg4/bin/awk (since the patch for bugID 5074811) treats it like 1.

1 Like

I am unable to use 1 with awk . Instead, I have to use nawk
I am on SunOS 5.10
I can use nawk , but just wondering why awk is not working with 1 on my machine :slight_smile:

You mean /usr/bin/awk. It works with /usr/xpg4/bin/awk.

@MadeInGermany

$3~/^$/

So this is the only solution that represent an empty filed.
Thanks for the information :slight_smile:

@juzzfun, Jotne: if you do not use quotes it will shave off the leading zero of 099990

1 Like

Could you please give me a pointer to the other thread?

I'm curious as to why you believe $3=="" should evaluate to 2 when $3 is an empty field. The standards say:

and a comparison expression is an expression using one of the operators < , <= , != , == , >= , or > .

Hi Don, may be you didn't read MadeInGermany's reply carefully (or may be it was not well explained). I think he meant that $3=="" is equivalent to $3~/^$/ (the 2nd code fragment in his post).

2 Likes

solaris keeps a stone-age awk around for compatibility reasons. To get the language everyone expects awk to be these days, you use nawk.

They still ship this in SysV R4.0 style i.e. link awk with oawk:

ls -li /usr/bin/*awk
     54765 -r-xr-xr-x   2 root     bin        89108 Oct  1  2007 /usr/bin/awk
     54744 -r-xr-xr-x   1 root     bin       126944 Oct  1  2007 /usr/bin/nawk
     54765 -r-xr-xr-x   2 root     bin        89108 Oct  1  2007 /usr/bin/oawk