Copying multiple files with the same name in the same script folder

I have many files with the same name, with this directory structure (simplified):

../foo1/bar1/dir/file_1.ps ../foo1/bar2/dir/file_1.ps ../foo2/bar1/dir/file_1.ps .... and many more 

As it is extremely difficult to browse all these ps files by going to the appropriate directory, I would like to copy all of them to another directory, but include the name of the first two directories (which match my purpose) in the file name.

I previously tried like this, but I can’t get which file is coming from, since they are all indicated sequentially:

 #!/bin/bash -xv cp -v --backup=numbered {} */*/dir/file* ../plots/; 

Where ../plots is the folder in which I copy them. However, they now have the form file.ps. ~ x ~ (x is a number), so I get rid of ".ps. ~ * ~" and leave only the ps extension with:

 rename 's/\.ps.~*~//g' *; rename 's/\~/.ps/g' *; 

Then, since ps files sometimes have hundreds of points and take a lot of time, I just convert them to jpg.

 for file in * ; do convert -density 150 -quality 70 "$file" "${file/.ps/}".jpg; done; 

This does not work bash script, since I need to manually change the directory.

I think the best way to do this is to copy the files from the beginning with the names of the first two directories included in the copied file name.

How can I do this last?

+4
source share
2 answers

If you have only two levels of directories, you can use

 for file in */*/*.ps do ln "$file" "${file//\//_}" done 

This happens through every ps file and hard links them to the current directory with the replacement of / by _ . Use cp instead of ln if you are going to edit files but do not want to update the originals.

For arbitrary directory levels you can use bash specific

 shopt -s globstar for file in **/*.ps do ln "$file" "${file//\//_}" done 

But are you sure you need to copy them all to the same directory? You might be able to open them all with yourreader */*/*.ps , which, depending on your reader, may allow you to view them in turn, still seeing the full path.

+6
source

You should run the find command and print the names first, e.g.

 find . -name "file_1.ps" -print 

Then iterate over each of them and replace the string / with '-' or any other character, for example

 ${filename/\//-} 

The general syntax is ${string/substring/replacement} . Then you can copy it to the desired directory. The full script can be written as follows. Have not tested it (and not on Linux at the moment), so you may need to tweak the code if you get a syntax error;)

 for filename in `find . -name "file_1.ps" -print` do newFileName=${filename/\//-} cp $filename YourNewDirectory/$newFileName done 

You will need to place the script in the same root directory or modify the find command to search for a specific directory if you put the above script in a different directory.

References

+1
source

All Articles