Issue
I am trying to replace a column from one file with a column from another file using AWK. The files are tab-delimited. The problem is that the second file has a header. Therefore the number of rows is not the same. I am not sure how to skip the 1st line in one file but not in the other. Any suggestions?
Thanks
For example:
Here I presented two hypothetical files (tab-delimited) where I want to replace the values from the 2nd column of file1 with the values from the 3rd column ("NewValue") of file2
file1:
"ID_1" | "U" | "Place1" |
"ID_2" | "U" | "Place2" |
file2:
"ID" | "Name" | "NewValue" |
---|---|---|
"ID_1" | "A" | "X" |
"ID_2" | "B" | "Y" |
Expected result:
"ID_1" | "X" | "Place1" |
"ID_2" | "Y" | "Place2" |
I tried with the following code, but it didn't work.
awk 'NR>1 && NR==FNR{a[NR]=$0;next} {$2=a[FNR]}1' file2 file1
Solution
Assuming you want to change fields based on the order of lines in each file rather than by the value of the ID
column as indicated by the code in your question and as stated in your comment then using any awk:
$ awk 'BEGIN{FS=OFS="\t"} NR==FNR{a[NR]=$3; next} {$2=a[FNR+1]} 1' file2 file1
"ID_1" "X" "Place1"
"ID_2" "Y" "Place2"
Answered By - Ed Morton Answer Checked By - Candace Johnson (WPSolving Volunteer)