user3311147
user3311147

Reputation: 291

replacing multiple columns with awk for specific lines

I want to replace columns 3, 4 and 5 of a.com with 6 , 7 and 8th columns of b.com for specific lines.

awk 'NR==FNR{a[NR]=$6;next}FNR>5&&FNR<5287{$3=a[FNR]}1' b.com a.com

-will replace columns one at a time. Can I modify this command so that it will replace all the three columns?

Eg:-

a.com:

a b 1 2 3 4
c d 3 2 1 4

b.com:

a d e f k 3 4 5 l
p q w e g 5 4 3 m

Desired output:

a b 3 4 5 4
c d 5 4 3 4

Upvotes: 1

Views: 1207

Answers (2)

jaypal singh
jaypal singh

Reputation: 77085

awk 'NR==FNR {fld6[NR]=$6; fld7[NR]=$7; fld8[NR]=$8; next}
FNR>5 && FNR<5287 {$3=fld6[FNR]; $4=fld7[FNR]; $5=fld8[FNR]}1' b.com a.com

Logic:

  • Store the columns you need from b.com into arrays indexed at line number
  • Once that similar line is reached in a.com, you replace the columns from b.com by referencing the array.
  • FNR>5 && FNR<5287 This is to modify these specific lines. For every line you can remove this

Test

$ cat a.com 
a b 1 2 3 4
c d 3 2 1 4

$ cat b.com 
a d e f k 3 4 5 l
p q w e g 5 4 3 m

$ awk 'NR==FNR {fld6[NR]=$6; fld7[NR]=$7; fld8[NR]=$8; next}
{$3=fld6[FNR]; $4=fld7[FNR]; $5=fld8[FNR]}1' b.com a.com
a b 3 4 5 4
c d 5 4 3 4

Upvotes: 2

philshem
philshem

Reputation: 25331

I would first use paste and then awk.

paste a.com b.com > c.com

This command puts a.com and b.com in a new file as adjacent columns.

Then to the awk part,

awk '{print $3,$4,$5,$10,$11,$12}' c.com

(You'll have to clean it up depending on how many columns were actually in a.com

As one command

paste a.com b.com | awk '{print $3,$4,$5,$10,$11,$12}'

edit: maybe this doesn't work if OP needs only specific rows (lines)

Upvotes: 0

Related Questions