Print Based on File Name

Morning,

I have an issue to print files based on file name
my input file

20170516_WATERSONGS.txt
20170509_MULTIFLAG.txt

every file consist of list of number, for ex 20170516_WATERSONGS.txt

7281370247390
7281370605338
7281370836600
7281370840039
7281372341119
7281372821958
7281374319089

20170509_MULTIFLAG.txt

2585296582710
2585296835209
2585296940311
2585297027737
2585297122509

I need to print all my input files as expected below

20170516|7281370247390|WATERSONGS
20170516|7281370605338|WATERSONGS
20170516|7281370836600|WATERSONGS
20170516|7281370840039|WATERSONGS
20170516|7281372341119|WATERSONGS
20170516|7281372821958|WATERSONGS
20170516|7281374319089|WATERSONGS
20170509|2585296582710|MULTIFLAG
20170509|2585296835209|MULTIFLAG
20170509|2585296940311|MULTIFLAG
20170509|2585297027737|MULTIFLAG
20170509|2585297122509|MULTIFLAG

I did this

awk 'FNR == 1 {nm=substr(FILENAME, length(FILENAME)-25, 8)}{mm=substr(FILENAME, length(FILENAME)-5, 8)} {print nm "|"mm"|" $0}' *.txt

please help

Hello radius,

Could you please try following and let me know if this helps you.

awk 'FNR==1{split(FILENAME, array,"_");sub(/\.txt/,"",array[2]);} {print array[1]"|"$0"|"array[2]}' 20170516_WATERSONGS.txt  20170509_MULTIFLAG.txt

Thanks,
R. Singh

1 Like

thanks, it works sir

Try:

awk 'FNR==1{split(FILENAME,F,/[_.]/)} {print F[1],$0,F[2]}' OFS=\| 20170516_WATERSONGS.txt 20170509_MULTIFLAG.txt

--
@ravindersingh, why not perform the sub() in the FNR section. Also . has a special meaning in regex...

1 Like