Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe the results of 'find' to mv in Linux

Tags:

linux

unix

How do I pipe the results of a 'find' (in Linux) to be moved to a different directory? This is what I have so far.

find ./ -name '*article*' | mv ../backup 

but its not yet right (I get an error missing file argument, because I didn't specify a file, because I was trying to get it from the pipe)

like image 715
user1015214 Avatar asked Mar 13 '14 19:03

user1015214


People also ask

How do you find mv?

The Momentum Calculator uses the formula p=mv, or momentum (p) is equal to mass (m) times velocity (v). The calculator can use any two of the values to calculate the third. Along with values, enter the known units of measure for each and this calculator will convert among units.

How do I pipe a command in Linux?

You can make it do so by using the pipe character '|'. Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

How do I find and move a file in Linux?

Moving on the command line. The shell command intended for moving files on Linux, BSD, Illumos, Solaris, and MacOS is mv. A simple command with a predictable syntax, mv <source> <destination> moves a source file to the specified destination, each defined by either an absolute or relative file path.

What is the output of find command in Linux?

The find command is used to search and locate the list of files and directories based on conditions you specify for files that match the arguments. find command can be used in a variety of conditions like you can find files by permissions, users, groups, file types, date, size, and other possible criteria.


2 Answers

find ./ -name '*article*' -exec mv {}  ../backup  \; 

OR

find ./ -name '*article*' | xargs -I '{}' mv {} ../backup 
like image 99
Amit Verma Avatar answered Oct 05 '22 00:10

Amit Verma


xargs is commonly used for this, and mv on Linux has a -t option to facilitate that.

find ./ -name '*article*' | xargs mv -t ../backup 

If your find supports -exec ... \+ you could equivalently do

find ./ -name '*article*' -exec mv -t ../backup {}  \+ 

The -t option is a GNU extension, so it is not portable to systems which do not have GNU coreutils (though every proper Linux I have seen has that, with the possible exception of Busybox). For complete POSIX portability, it's of course possible to roll your own replacement, maybe something like

find ./ -name '*article*' -exec sh -c 'mv "$@" "$0"' ../backup {} \+ 

where we shamelessly abuse the convenient fact that the first argument after sh -c 'commands' ends up as the "script name" parameter in $0 so that we don't even need to shift it.

like image 37
tripleee Avatar answered Oct 05 '22 00:10

tripleee