How copy and rename files found in "find" function Linux?

Here you go:

for file in /home/user/temps/*/thumb.png; do new_file=${file/temps/new_folder}; cp "$file" "${new_file/\/thumb/}"; done;

edit:

the canonical wisdom, by the way, is that using find for this is a bad idea -- simply using shell expansion is much more reliable. Also, this assumes bash, but I figure that's a safe assumption :)

edit 2:

for clarity, I'll break it down:

# shell-expansion to loop specified files
for file in /home/user/temps/*/thumb.png; do

    # replace 'temps' with 'new_folder' in the path
    # '/home/temps/abc/thumb.png' becomes '/home/new_folder/abc/thumb.png'
    new_file=${file/temps/new_folder};

    # drop '/thumb' from the path
    # '/home/new_folder/abc/thumb.png' becomes '/home/new_folder/abc.png'
    cp "$file" "${new_file/\/thumb/}";
done;

details on the ${var/Pattern/Replacement} construct can be found here.

the quotes in the cp line are important to handle spaces and newlines etc. in filenames.


This works for arbitrarily deep subdirectories:

$ find temps/ -name "thumb.png" | while IFS= read -r NAME; do cp -v "$NAME" "separate/${NAME//\//_}"; done
`temps/thumb.png' -> `separate/temps_thumb.png'
`temps/dir3/thumb.png' -> `separate/temps_dir3_thumb.png'
`temps/dir3/dir31/thumb.png' -> `separate/temps_dir3_dir31_thumb.png'
`temps/dir3/dir32/thumb.png' -> `separate/temps_dir3_dir32_thumb.png'
`temps/dir1/thumb.png' -> `separate/temps_dir1_thumb.png'
`temps/dir2/thumb.png' -> `separate/temps_dir2_thumb.png'
`temps/dir2/dir21/thumb.png' -> `separate/temps_dir2_dir21_thumb.png'

The interessting part is the parameter expansion ${NAME//\//_}. It takes the content of NAME, and replaces every occurence of / with _.

Note: the result is dependent on the working directory and the path parameter for find. I executed the command from the parent directory of temps. Replace cp with echo to experiment.

Tags:

Shell

Rename

Find