UNIX script to append multiple text files into one file based on pattern present in filaname

Hi All-I am new to Unix , I need to write a script. Can someone help me with a requirement where I have list of files in a directory, I want to Merge the files if a pattern of string matches in filenames?

AAAL_555A_ORANGE1_F190404.TXT
AAAL_555A_ORANGE2_F190404.TXT
AAAL_555A_ORANGE3_F190404.TXT
AAAL_555A_ORANGE4_F190404.TXT
AAAL_555A_MANGO_F190404.TXT
AAAL_555A_MANGO2_F190404.TXT
AAAL_555B_APPLE_F190404.TXT
AAAL_555B_ORANGE_F190404.TXT
AAAL_555B_Orange_F190404.TXT

If second part of filename='555A' and third part consists of ORANGE then all Oranges/555A content files will merger into one file with filename as AAAl_555A_ORANGE.txt.

If second part of filename='555B' and third part consists of ORANGE/555B then all Oranges content files will merger into one file with filename as AAAl_555B_ORANGE.txt.

If second part of filename='555A' and third part consists of MANGO then all Mango content files will merger into one file with filename as AAAl_555A_MANGO.txt, etc.

Kindly help ..!

Did you try something yourself ?

I can offer some hints, awk FILENAME variable, awk split

Regards
Peasant.

And what should happen to the APPLE file?

In the same way APPLE files also should get merge . If i got an idea on Orange and Mango later i will add logic for remaining files. I highly appreciate your help.

Please answer Peasant's question.

Yes please , Kindly share the hints.

Hello Shankar455,

I have a few to questions pose in response first:-

  • Is this homework/assignment? There are specific forums for these.
  • What have you tried so far?
  • What output/errors do you get?
  • What OS and version are you using?
  • What are your preferred tools? (C, shell, perl, awk, etc.)
  • What logical process have you considered? (to help steer us to follow what you are trying to achieve)

Most importantly, What have you tried so far?

There are probably many ways to achieve most tasks, so giving us an idea of your style and thoughts will help us guide you to an answer most suitable to you so you can adjust it to suit your needs in future.

The logic isn't very explicit I'm afraid. Can you break it down into simpler steps? Something like:-
For every file

  • Get the value F1 for the first field (underscore separated)
  • Get value F2 the second field (underscore separated)
  • Get the F3 third field (underscore separated)
  • Write the content of the file to F1_F2_F3.txt

Are you really just looking to write all the files that match the 1st, 2nd & 3rd parts of the filename to a common file?

I might have missed the point of your original question. Please can you be specific and lay out your logic to make sure we help you in the right way. That will also help you to have a go yourself that we can then help with. We're all here to learn and getting the relevant information will help us all.

Kind regards,
Robin