Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving files with an extension into a location

Tags:

How could I move all .txt files from a folder and all included folders into a target directory .

And preferably rename them to the folder they where included in, although thats not that important. I'm not exactly familiar with bash.

like image 815
Gunslinger Avatar asked Jan 15 '13 19:01

Gunslinger


People also ask

How do I move a file to a different location?

Right-click the file or folder you want, and from the menu that displays click Move or Copy. The Move or Copy window opens. Scroll down if necessary to find the destination folder you want.

How do I move a file to a different location in Windows?

Highlight the files you want to move, press and hold your right mouse button, and drag-and-drop the files to where you want to move them. When you release the mouse button, a menu appears, similar to the example shown in the picture. Select the Move here option to move the files.

How do I copy a file with a specific extension in Windows?

To copy the files with the specific extension, you need to use the Get-ChildItem command. Through the Get-ChildItem you first need to retrieve the files with the specific extension(s) and then you need to pipeline Copy-Item command.


2 Answers

To recursively move files, combine find with mv.

find src/dir/ -name '*.txt' -exec mv -t target/dir/ -- {} + 

Or if on a UNIX system without GNU's version of find, such as macOS, use:

find src/dir/ -name '*.txt' -exec mv -- {} target/dir/ ';' 

To rename the files when you move them it's trickier. One way is to have a loop that uses "${var//from/to}" to replace all occurrences of from with to in $var.

find src/dir/ -name '*.txt' -print0 | while IFS= read -rd $'\0' file; do     mv -- "$file" target/dir/"${file//\//_}" done 

This is ugly because from is a slash, which needs to be escaped as \/.

See also:

  • Unix.SE: Understanding IFS= read -r line
  • BashFAQ: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?
like image 98
John Kugelman Avatar answered Sep 19 '22 03:09

John Kugelman


Try this:

find source -name '*.txt' | xargs -I files mv files target 

This will work faster than any option with -exec, since it will not invoke a singe mv process for every file which needs to be moved.

like image 37
Mithrandir Avatar answered Sep 19 '22 03:09

Mithrandir