RKG
RKG

Reputation: 41

How to replace row with another row in linux

I have file 1:

A1  1  NA
A1  2  NA
A1  3  NA
A1  4  A
A1  5  G
A1  6  T
A1  7  NA
A1  8  NA
A1  9  NA
A2  1  NA
A2  2  NA
A2  3  T
A2  4  NA

And file 2:

A1  4  A
A1  5  B
A1  6  T
A2  3  T

I want to replace row number 4,5,6 and 3 of A2 from file 1 with a value of 4,5,6 and 3 from file 2

Expected Output in new file3:-

A1  1  NA
A1  2  NA
A1  3  NA
A1  4  A
A1  5  B
A1  6  T
A1  7  NA
A1  8  NA
A1  9  NA
A2  1  NA
A2  2  NA
A2  3  T
A2  4  NA

I want to try this in Linux. I tried googling but I could not find better answers.

Upvotes: 3

Views: 411

Answers (3)

user000001
user000001

Reputation: 33317

Another alternative, with awk:

awk 'NR==FNR{a[$1,$2]=$0;next} ($1,$2) in a {$0=a[$1,$2]}1' file2 file1
A1  1  NA
A1  2  NA
A1  3  NA
A1  4  A
A1  5  B
A1  6  T
A1  7  NA
A1  8  NA
A1  9  NA
A2  1  NA
A2  2  NA
A2  3  T
A2  4  NA

Upvotes: 1

user9549915
user9549915

Reputation:

Using join:

join -a 2 file2 file1 | cut -d ' ' -f -2

Where file1 is the original file and file2 is the file with the replacement fields.


Edit: The question's requirements have been changed since posting this; it originally asked for joining two files with two columns each. For the new format, this awk script works:

cat file1 file2 | awk '
  BEGIN { OFS = "  " }
  { rows[$1 OFS $2] = $3 }
  END { for (r in rows) print(r, rows[r]) }
' | sort -V >file3

Output using the files specified in the question:

$ cat file3
A1  1  NA
A1  2  NA
A1  3  NA
A1  4  A
A1  5  B
A1  6  T
A1  7  NA
A1  8  NA
A1  9  NA
A2  1  NA
A2  2  NA
A2  3  T
A2  4  NA

Upvotes: 1

Akshay Shetty
Akshay Shetty

Reputation: 1

If you've inserted the data in the file using a structure,you can use the same structure to retrieve the nth entry using a loop and replace it respectively!

Else if you've inserted data manually,you could just traverse the file for (n-1) number of '\n' and retrieve the following data!

Upvotes: 0

Related Questions