Shahin
Shahin

Reputation: 1316

replacing associative array indexes with their value using awk or sed

I would like to replace column values of ref using key value pairs from id

cat id:

[1] a 8-23
[2] g 8-21
[3] d 8-13

cat ref:

a 1 2
b 3 4
c 5 3
d 1 2
e 3 1
f 1 2
g 2 3

desired output

8-23    1   2
b       3   4
c       5   3
8-13    1   2
e       3   1
f       1   2
8-21    2   3

I assume it would be best done using awk.

cat replace.awk

BEGIN { OFS="t" }

NR==FNR {
    a[$2]=$3; next
}

$1 in !{!a[@]} {

print $0
}

Not sure what I need to change?

Upvotes: 0

Views: 220

Answers (1)

jhnc
jhnc

Reputation: 16817

$1 in !{!a[@]} is not awk syntax. You just need $1 in a:

BEGIN { OFS='\t' }

NR==FNR {
    a[$2] = $3
    next
}

{
    $1 = ($1 in a) ? a[$1] : $1
    print
}
  • to force OFS to update, this version always assigns to $1
  • print uses $0 if unspecified

Upvotes: 1

Related Questions