Reputation: 79
I was looking out for a file replacement functionality to be done in awk
. I had a solution that worked well for Red Hat Linux flavour but it is not working well with SunOS 5.10. It would be great if someone can help troubleshoot the issue.
Source file (src.txt)
aaaa
uid=xxxx
pwd=nnnn
u_no=12345
bbbb
uid=yyyy
pwd=eeee
zzzz
uid=yyyy
pwd=eeee
Reference file (ref.txt)
block,parameter,value
aaaa,uid,1a1a
aaaa,pwd,1b1b
bbbb,uid,2a2a
zzzz,pwd,9b9b
zzzz,uid,9a9a
bbbb,pwd,2b2b
Required output file (tgt.txt)
The target file should be an updated source file based on the lookup values from the reference file as follows:
aaaa
uid=1a1a
pwd=1b1b
u_no=12345
bbbb
uid=2a2a
pwd=2b2b
zzzz
uid=9a9a
pwd=9b9b
Code
awk -F= '
FNR==NR {
split($0,b,",")
a[b[1] FS b[2]]=b[3]
next}
!/=/ {
f=$1
print
next}
{
print $1"="(a[f FS $1]?a[f FS $1]:$2)}
' ref.txt src.txt > tgt.txt
The code solution was given by one of our friends here in Stack Overflow and it worked pretty well in Red Hat Linux.
When I tried to copy it to SunOS 5.10, it first showed a syntax error at:
!/=/ {
I replaced the field separator value and it stopped showing syntax error.
OFS="="
For this, the script executes, but just prints the source file values (not an updated value).
Can you help me find a solution for this?
Upvotes: 3
Views: 1118
Reputation: 30843
Use nawk
(new awk) or /usr/xpg4/bin/awk
(POSIX awk) with Solaris. awk
is the original legacy version.
Here is something that works:
nawk -F= '
FNR==NR {
split($0,b,",")
a[b[1] FS b[2]]=b[3]
next}
$0 !~ "=" {
f=$1
print
next}
{
print $1"="(a[f FS $1]?a[f FS $1]:$2)}
' ref.txt src.txt > tgt1.txt
Upvotes: 3