0

In a directory I have the following files:

lebron_2018.txt lebron_2019.txt

melo_2018.log melo_2019_01.log

wade_2018.bak wade_2019_02.jpg

All the files has delimiter of "_", I would like to copy the files to different new directory according to the prefix. For example

lebron_2018.txt lebron_2019.txt will copy to \backup\lebron

melo_2018.log melo_2019_01.log will copy to \backup\melo

wade_2018.bak wade_2019_02.jpg will copy to \backup\wade

I can do it by cp lebron*.* \backup\lebron. But can it be done by searching the filename, and copy to the folder according to their filename automatically?

2 Answers2

0

Lots of nice ideas in @AdminBee linked post but it just feels right to execute a loop only for each pattern that can be globbed.

Assuming no whitespace:

for f in $(ls *_*.txt | cut -d_ -f1 | uniq); do
    mkdir -p ./backup/$f;
    cp $f_*.txt ./backup/$f/;
done
bu5hman
  • 4,756
0

Your slashes are going the wrong way for a *nix system. Should work as long as you have no spaces or exotic characters in the file names.

for FILE in *_*.txt ; do
  DIR="/backup/${FILE//_*}"
  mkdir -p "${DIR}" || continue
  mv "${FILE}" "${DIR}"
done

Uses bash variable expansion to snip the name off the file to make the directory. Plays safe by skipping items where it can’t create the directory (to prevent data loss).

bxm
  • 4,855