0

I have two directories (cofactors and set) and I need to concatenate the files that match a string on their names. For example, for file names that contains "aloha" and "boo" I would like to do this:

cat cofactors/aloha_12345.txt set/aloha_clean.txt >> aloha_12345.txt
cat cofactors/boo_5675.txt set/boo_7890.txt >> boo_5675.txt

I've been testing with some loops but can't get it right:

for c in set/*.pdb; do echo $c; if awk -F '[/_]' '{print $2}' in cofactors/*.pdb then echo cofactors/*.pdb; done
Marcos Santana
  • 911
  • 5
  • 12
  • 21
  • 1
    what if there one file `cofactors/aloha_12345.txt` and 2 files `set/aloha_clean.txt` , `set/aloha_other.txt` ? – RomanPerekhrest Dec 13 '17 at 14:56
  • Just edited it. I'm looking for strings on the file name. – Marcos Santana Dec 13 '17 at 14:56
  • In this case there is only one file in set/ and one in cofactors/. But if there are more files I wish to concatenate all of them if they match a string on the file name. – Marcos Santana Dec 13 '17 at 14:59
  • Possible duplicate of https://stackoverflow.com/questions/28725333/looping-over-pairs-of-values-in-bash – tripleee Dec 13 '17 at 15:01
  • 1
    Your specification is not 100% complete. 1) how do you chose the name of the output file? 2) in what order to you want to concatenate the matching files? 3) when you write *file names that contains "`aloha`"* do you mean *file names that **start** with "`aloha`"* or can "`aloha`" match at any position in the file name? – Renaud Pacalet Dec 13 '17 at 15:50

1 Answers1

3

Perhaps this algorithm can help:

  • for each $file in cofactors
  • take the prefix of the filename before the first _
  • concatenate the file and set/${prefix}_* to $file

Like this:

shopt -s nullglob

for f in cofactors/*; do
    basename=${f##*/}
    prefix=${basename%%_*}
    cat "$f" "set/${prefix}_"* > "$basename"
done

(Thanks @socowi for the improvements!)

janos
  • 120,954
  • 29
  • 226
  • 236
  • 1
    I think you meant to glob the files in `set/`, so the last star shouldn't be quoted. It might also be helpful to enable `shopt -s nullglob` for cases when there are no matching files in `set/`. – Socowi Dec 14 '17 at 00:18