Pick a column from one file while working with awk on 2 files

Hi,
I am trying to understand a part of my existing code built by someone else and also try to bring in one more column in the output.
I have two files as below:
CSV file 1:

Scorecard_1,ZDTJ_PREV.EXT,12
Scorecard_2,ZACN_PREV.EXT,6
Scorecard_3,ABC.txt,8

Text file 2:

Acct_Bal_Non_Zero_Tgt.txt,7243
IDQ_HB1.txt,5380
IDQ_HB_LOGC.txt,5380
ZACN_PREV.EXT,4
ZDTJ_PREV.EXT,3
ABC.txt,10

Below is the piece of code:

awk '
BEGIN{
FS=OFS=","
}
FNR==NR{
arr[$2]=$NF
next
}
{
print $1,(($1 in arr)?($NF>arr[$1]?"Previous_Day_File":"Current_Day_File"):"No_Match")
}
' file1.csv file2.txt

I want to bring in col 1 from first file as well in my print output.
The script identifies the age of file and categorize as old or new file .
File 1 holds the filename and the interval (last column). File 2 holds the filename and the time difference ( last column which is calculated after current time-last modification time).
Now I just want to add col1 from first file as well in my output.

I don’t know how to do it with awk. But, you can redirect the output to a file, and then change the lines with sed:

awk '
BEGIN{
FS=OFS=","
}
FNR==NR{
arr[$2]=$NF
next
}
{
print $1,(($1 in arr)?($NF>arr[$1]?"Previous_Day_File":"Current_Day_File"):"No_Match")
}
' file1.csv file2.txt > out

while IFS=',' read -r col1 col2 col3
do
    sed -i "s/$col2/$col1,$col2/g" out
done < file1.csv

cat out

Thanks @artix-- I ran the script but I am getting the error
sed: -i expression #1, char 9: unknown option to `s

After removing the " with ’ it ran fine but I am still getting only 2 columns in the output.

maybe one of your filenames has a ‘/’ .

try changing the sed line to:

sed -i "s|$col2|$col1,$col2|g" out

No the filename doesn’t have any /. I tried with the suggested code but still getting two columns.

try this:

awk '
BEGIN{
FS=OFS=","
}
FNR==NR{
arr[$2]=$NF
nam[$2]=$1
next
}
{
print nam[$1]","$1,(($1 in arr)?($NF>arr[$1]?"Previous_Day_File":"Current_Day_File"):"No_Match")
}
' file1.csv file2.txt
1 Like

@artix --Thanks Much!! This is working as expected !!


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki