2

I am trying to rename files with the same names in different subdirectories using for loop.They should be renamed according to the name of subdirectory.

Subdirectory1/File.txt
Subdirectory2/File.txt

should look like

Subdirectory1/Subdirectory1.txt
Subdirectory2/Subdirectory2.txt

I tried many commands and I am getting different errors. The last command, which I found on forum also doesn't work. Can somebody help me?

dir="Subdirectory1, Subdirectory2"
declare -i count=1 for file in "$dir"/*.txt; do
mv "$file" "${dir}/${dir} ${count}.txt"
count+=1
done

After running this, I get:

mv: cannot stat ‘/*/*.txt’: No such file or directory

1 Answer 1

1

You can use code like this.

#!/bin/bash

# Loop across the list of directories
for dir in Subdirectory1 Subdirectory2
do
    # Only consider directories
    [ -d "$dir" ] || continue

    # Loop across any files in each directory
    for src in "$dir"/*.txt
    do
        dst="$dir/$dir.txt"
        
        # Only rename a file if it won't overwrite another one
        if [ -f "$dst" ]
        then
            # Refuse to overwrite
            echo "Target file already exists: $dst" >&2
        else
            # If the file already has the right name just skip
            [ -f "$src" ] && [ "$src" != "$dst" ] && mv -f -- "$src" "$dst"
        fi
    done
done

Prepare the script (let's say it's called renamethem) with chmod a+x renamethem. And then run it as ./renamethem.

You'll see the list of directories is hard-coded in the for loop. There are a couple of other ways to handle this a little more elegantly. You could provide the list on the command line (./renamethem Subdirectory1 Subdirectory2) in which case change one line to for dir in "$@" to pick the parameters from that command line. Or you could use an array (list). Or you could use * to match all directories in the current directory.

2
  • Thank you very much! It finally works :D
    – narm
    Commented Apr 28, 2021 at 13:36
  • If this answer solved your issue please would you accept it with the ✔ tickmark in the corner. This shows everyone else that this solution worked best for you and that your question has been answered successfully Commented Apr 28, 2021 at 14:00

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.