-1

I've a certain amount of files always containing same name but different extensions, for example sample.dat, sample.txt, etc. I would like to create a script that looks where sample.dat is present and than moves all files with name sample*.* into another directory.

I know how to identify them with ls *.dat | sed 's/\(.*\)\..*/\1/', however I would like to concatenate with something like || mv (the result of the first part) *.* /otherdirectory/

Cœur
  • 37,241
  • 25
  • 195
  • 267
Artur
  • 1
  • 1
  • [Move files to directories based on extension](https://stackoverflow.com/q/17334014/608639), [Copy all files with a certain extension from all subdirectories](https://stackoverflow.com/q/15617016/608639), [Move all files with a certain extension from multiple subdirectories into one directory](https://unix.stackexchange.com/q/67503/56041), etc. – jww Jul 19 '18 at 13:11

3 Answers3

-1

You can use this bash one-liner:

for f in `ls | grep YOUR_PATTERN`; do mv ${f} NEW_DESTINATION_DIRECTORY/${f}; done

It iterates through the result of the operation ls | grep, which is the list of your files you wish to move, and then it moves each file to the new destination.

pptaszni
  • 5,591
  • 5
  • 27
  • 43
-1

Something simple like this?

dat_roots=$(ls *.dat | sed 's/\.dat$//')
for i in $dat_roots; do
    echo mv ${i}*.* other-directory
done

This will break for file names containing spaces, so be careful.

Or if spaces are an issue, this will do the job, but is less readable.

ls *.dat | sed 's/\.dat$//' | while read root; do
    mv "${root}"*.* other-directory
done
Jon
  • 3,573
  • 2
  • 17
  • 24
  • And the second suggestion will break if the file names contain shell meta characters. If that is a problem, it's time to use Perl or Python :-) – Jon Jul 19 '18 at 13:49
  • Thnak you, ind it does what I need for now, a more efficient approach will be developped later. KR – Artur Jul 19 '18 at 15:04
  • @ArturFonseca Great! Can I have the accepted answer, please? Thanks! – Jon Jul 19 '18 at 15:50
-1

Not tested, but this should do the job:

shopt -s nullglob
for f in *.dat
do
    mv ${f%.dat}.* other-directory
done

Setting the nullglob option ensures that the loob is not executed, if no dat-file exists. If you use this code as part of a larger script, you might want to unset it afterwards (shopt -u nullglob).

user1934428
  • 19,864
  • 7
  • 42
  • 87