0

I have two files that I want to concatenate in one new file, but I want to do it by using a loop because I have different directories (a, b, c, g and z) with same 2 files. My loop is:

for i in a b c g z
do
    (cd $i/; for i in File_*_best3.txt *_new3.txt; do cat $i > combined.txt; done)
done

But my result is a combined.txt file exactly the same as my second input file, so my cat is not working properly. What is the issue here?

1
  • 1
    Don't use the same variable for the loop and inside the loop to mean different things. for $i in and your cat $i are logically meaning different things. maybe use d for the directories, or something. Commented Feb 9, 2017 at 18:17

2 Answers 2

1

The issue is that each time cat is executed, the output file is truncated (emptied). This is because you use > for redirection.

Alternative:

for d in a b c g z
do
    (cd "$d"; rm -f combined.txt; for i in File_*_best3.txt *_new3.txt; do cat "$i" >>combined.txt; done)
done

or

for d in a b c g z
do
    (cd "$d" && cat File_*_best3.txt *_new3.txt >combined.txt)
done

I'm assuming that File_*_best3.txt and *_new3.txt only matches one filename each.

0
0

Another solution without cd:

for d in a b c g z; do
    cat $d/{File_*_best3.txt,*_new3.txt} >$d/combined.txt
done
2
  • Did not work, I got some errors like - cat: 'a/{File_*_best3.txt,': No such file or directory
    – Alex
    Commented Feb 9, 2017 at 18:32
  • Maybe your shell can handle that!? I've used bash. Probably "cat $d/File_*_best3.txt $d/*_new3.txt" would work for you.
    – rudimeier
    Commented Feb 9, 2017 at 19:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .