Insert value of column based on file name matching

At the top of the XYZ file, I need to insert the ABC data value of column 2 only when ABC column 1 matches the prefix XYZ file name (not the ".txt"). Is there an awk solution for this?

ABC Data

0101	0.54
0102	0.48
0103	1.63

XYZ File Name

0101.txt
0102.txt
0103.txt

Expected output
XYZ File Name

> -Z0.54
abcdefg
123456

How about this bash solution:

declare -A TMP
while read A B; do TMP[$A]=$B; done < ABC
while read A; do echo ${TMP[${A%.*}]} | cat - $A; done < XYZ

Thanks for replying Rudy.

Just to be clear I have a single ABC file but multiple XYZ files.

I did not get your code to work on a either a single or multiple XYZ files.

Any other options?

Actually, I was wildly guessing WHAT your spec could mean. My proposal worked fine with three files whose names were listed in a "file name" file which in turn was matched against an ABC data file.

Obviously my interpretation regarding your file structure was wrong. Please post the file structure in your directory and some sample files.

I hope this makes sense.

File ABC

0101    0.54
0102    0.48

File 0101.txt

-111   34
-111   33
-111   33

File 0102.txt

-112   34
-112   33
-112   33

Expected output

File 0101-new.txt

> -Z0.54
-111   34
-111   33
-111   33

Expected output

File 0102-new.txt

> -Z0.48
-112   34
-112   33
-112   33

So - here's the results:

declare -A TMP
while read A B; do TMP[$A]=$B; done <ABC
while read A; do echo ${TMP[${A%.*}]} | cat - $A > ${A}.new; done < XYZ
cf 010?.txt.new
0101.txt.new:
0.54
-111   34
-111   33
-111   33
0102.txt.new:
0.48
-112   34
-112   33
-112   33
0103.txt.new:
1.63
-113   34
-113   33
-114   33

What be the errors that you encounter?

awk version:

awk '
  NR==FNR {
    A[$1]=$2
    next
  }
  FNR==1 {
    close(f)
    split(FILENAME,F,".")
    f=F[1] "-new." F[2]
    print "> -Z" A[F[1]] > f
  }
  {
    print >f
  }
' abc [0-9][0-9][0-9][0-9].txt

I think that file ABC has all the information.

while read c1 c2
do
 fname="$c1.txt"
 {
  echo "> -Z$c2"
  cat "$fname"
 } >"$fname.new"
done <"ABC"
1 Like