6
$ cat file
/tmp/foldera/folderb/folderc/file1
/tmp/folderc/folderd/foldere/file2
/tmp/folderf/folderg/folderh/file3

Need to move this files to

/tmp/foldera/
/tmp/folderc/
/tmp/folderf/

respectively using a loop or any easy handy way to do that.

10

Use a while loop:

while IFS= read -r l; do
  mv -v -- "$l" "${l%/*/*/*}/"
done <file
  • while IFS= read -r l will read the file line by line.
  • mv -v move the files and -v tells mv to be verbose
    • "$l" is the source filename
    • "${l%/*/*/*}/" is the target directory. It removes 3 slashes and what is between them (/*/*/*) from the back end of the filename.

This will produce:

»/tmp/foldera/folderb/folderc/file1“ -> »/tmp/foldera/file1“
»/tmp/folderc/folderd/foldere/file2“ -> »/tmp/folderc/file2“
»/tmp/folderf/folderg/folderh/file3“ -> »/tmp/folderf/file3“
6

I'll suggest a similar answer as chaos, but using dirname

while IFS= read -r l; do
    mv -- "$l" "$(dirname -- "$(dirname -- "$l")")"
done <file

dirname reports the path of the directory a file/directory is located in. This has the advantage of being able to handle moving a directory as well, in case your file has an entry like:

/tmp/foldera/folderb/folderc/folderd/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.