quik1399
quik1399

Reputation: 185

Move file to a directory with a given condition using Bash

First of all, thank you for your help. I have a problem trying to move a file to a directory. I have the next directories: Animals Boat Carsand I want to move the following files Animals.txt Boat.txt and Car.txt I want to do it so if the name of the file matches the name of the directory it moves to it, instead of doing the following code:

mv Animals.txt Animals

Upvotes: 0

Views: 1159

Answers (4)

mattb
mattb

Reputation: 3062

If you install mmv, you can do it without a loop in one line (I'm assuming the directories already exist):

mmv '*.txt' '#1'

I you wanted to pull the files out of the directories (i.e. reverse the above process) you would do:

mmv '*/*' '#2'

Upvotes: 0

oguz ismail
oguz ismail

Reputation: 50815

Seems like all you need is a simple loop and a parameter expansion to derive directory names from file names.

for txt in ./*.txt; do
  dir=${txt%.*}
  if [ -d "$dir" ]; then
    echo mv "$txt" "$dir"
  fi
done

Drop echo if the output looks good.

Upvotes: 2

Tobias Fendin
Tobias Fendin

Reputation: 185

Edit: This answer doesn't work as expected, I missed the part about missing directories. The answer given by @oguz-ismail is better.

mkdir animals boat cars
touch animals.txt boat.txt cars.txt
for f in *.txt; do mv -v $f ${f/.txt}; done
renamed 'animals.txt' -> 'animals/animals.txt'
renamed 'boat.txt' -> 'boat/boat.txt'
renamed 'cars.txt' -> 'cars/cars.txt'

Upvotes: 1

Bodo
Bodo

Reputation: 9895

This script will move all *.txt files of the current directory into the corresponding directory if such a directory exists.

for f in *.txt
do
    # Avoid possible errors or unwanted commands in case there is no match for *.txt
    if [ "$f" != '*.txt' ]
    then
        # strip trailing .txt
        d="${f%.txt}"
        # check if corresponding directory exists
        if [ -d "$d" ]
        then
            mv "$f" "$d"
        fi
    fi
done

Upvotes: 2

Related Questions