Copying multiple files with same name in the same folder terminal script
bash, copy, rename, scripting
Solution
If you just have two levels of directories, you can use
for file in */*/*.ps
do
ln "$file" "${file//\//_}"
done
This goes over each ps file, and hard links them to the current directory with the `/`s replaced by `_`. Use `cp` instead of `ln` if you intend to edit the files but don't want to update the originals.
For arbitrary directory levels, you can use the 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 one directory? You might be able to open them all with `yourreader */*/*.ps`, which depending on your reader may let browse through them one by one while still seeing the full path.
Problem
I have a lot of files named the same, with a directory structure (simplified) like this: ``` ../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 inefficient to view all of those ps files by going to the respective directory, I'd like to copy all of them into another directory, but include the name of the first two directories (which are those relevant to my purpose) in the file name. I have previously tried like this, but I cannot get which file is from where, as they are all named consecutively: ``` #!/bin/bash -xv cp -v --backup=numbered {} */*/dir/file* ../plots/; ``` Where `../plots` is the folder where I copy them. However, they are now of the form file.ps.~x~ (x is a number) so I get rid of the ".ps.~*~" and leave only the ps extension with: ``` rename 's/\.ps.~*~//g' *; rename 's/\~/.ps/g' *; ``` Then, as the ps files have hundreds of points sometimes and take a long time to open, I just transform them into jpg. ``` for file in * ; do convert -density 150 -quality 70 "$file" "${file/.ps/}".jpg; done; ``` This is not really a working bash script as I have to change the directory manually. I guess the best way to do it is to copy the files form the beginning with the names of the first two directories incorporated in the copied filename. How can I do this last thing?