Use a cycle in bash with cat

1

I am using cat in bash to merge several files into one, as there are more than a thousand folders I do not want to do an instruction for each folder, how can I do a cycle so you can go through all the folders and join the files of the respective folders.

What I do to join the files is the following code:

cat /media/user/PENDRIVE/test/0b8/2014322/2014322_0b8*.msd > /media/user/PENDRIVE/test/0b8/2014322/2014322_0b8.msd

cat /media/user/PENDRIVE/test/0b8/2014323/2014323_0b8*.msd > /media/user/PENDRIVE/test/0b8/2014323/2014323_0b8.msd

cat /media/user/PENDRIVE/test/0b8/2014324/2014324_0b8*.msd > /media/user/PENDRIVE/test/0b8/2014324/2014324_0b8.msd

How could I do it?

    
asked by Armando 27.01.2016 в 22:52
source

1 answer

5

First of all, your question is too generic, you should try to granulate it more, for example you could ask how to list the folders that are in a particular location but not to a lesser or greater depth.

To answer your question, what you can do is, list the folders that are inside the /media/user/PENDRIVE/test/0b8 folder and process the output within a cycle, for example:

find /media/user/PENDRIVE/test/0b8 -mindepth 1 -maxdepth 1 -mindepth 1 -type d | while read d; do echo $d; done

What you see in the output, is the complete path to each of the folders you found. Then you can use the basename command to change the name of the folder to a variable in the following way:

find /media/user/PENDRIVE/test/0b8 -mindepth 1 -maxdepth 1 -mindepth 1 -type d | while read d; do dname=$(basename $d); echo $dname; done 

This should give you the name of the folder without the entire route. Then you can use the two variables that you have to execute the cat command that you mention in the question:

find /media/user/PENDRIVE/test/0b8 -mindepth 1 -maxdepth 1 -mindepth 1 -type d | while read d; do dname=$(basename $d); cat "$d/$dname"_0b8*.msd > cat "$d/$dname"_0b8.msd ; done

You can debug the script on a line using the set -x statement and disable debugging using the set +x command and you can also use it as follows before executing the final version:

find /media/user/PENDRIVE/test/0b8 -mindepth 1 -maxdepth 1 -mindepth 1 -type d | while read d; do dname=$(basename $d); echo cat "$d/$dname"_0b8*.msd ">" cat "$d/$dname"_0b8.msd ; done

You should only remove the echo when you see that the commands that are executed in the while loop are correct

    
answered by 28.01.2016 / 00:49
source