Concatenate files based on names

Dear all,
I have a list of files and I woulk like to concatenate some of them based on their name.
Basically my files are names like that:

file1_abcd_other_useless_letters_1_C1.txt
file1_abcd_other_useless_letters_1_C2.txt
file1_xywz_other_useless_letters_1_C1.txt
file1_xywz_other_useless_letters_1_C2.txt
file2_abcd_other_useless_letters_2_C1.txt
file2_abcd_other_useless_letters_2_C2.txt
file2_xywz_other_useless_letters_2_C1.txt
file2_xywz_other_useless_letters_2_C2.txt

Basically, I woul like the files with the same color to be concatenate.
Output:

abcd_other_useless_letters_C1.txt (merge of file1_abcd_other_useless_letters_1_C1.txt & file2_abcd_other_useless_letters_2_C1.txt )
abcd_other_useless_letters_C2.txt
xywz_other_useless_letters_C1.txt
xywz_other_useless_letters_C2.txt

That means (suppose

_

as separator) ,for the merged files

1)first field

file

should be different
2) second field

abcd

should be the same
3) fields

other_useless_letters

should not be considered at all
4) second to last field

1

should be different
5) last field

C1

should be the same

well, I think that the color code of file is still the better explanation

Hope someone can help me.

Best

Giuliano

Would this do (not too old bourne type shell required)?

ls f*.txt |
while read FN
  do    IFS="_." read X P1 O1 U1 L1 N1 P2 EX <<< $FN
        NFN="${P1}_${O1}_${U1}_${L1}_${P2}.${EX}"
        touch $NFN
        cat $FN >> $NFN
  done
1 Like

It works great!

Thanks!

As you may have noticed, there is no check for the number in the second last field to be different. Should that be compulsory, we'd need to insert some additional processing (and mayhap another new file name definition).

Actually that number is useless so is fine like that...it's always different if first field is different..

Thanks

Giuliano