Michael Gifford
Michael Gifford

Reputation: 25

Linux Script to move directories containing a file

Fairly new to scripting in linux, so I'm hoping this is something simple. I need to move a directory containing several files to another location if that directory contains a file with a certain piece of text in it.

I have a command that gives me a list of directories matching my criteria here:

find . -name 'file.name' -print0 | xargs -0 grep -l "foo" | sed 's#\(.*\)/.*#\1#' | sort -u

Now I just need to take the results of this and combine them with an mv command inside of an executable script.

Upvotes: 1

Views: 880

Answers (3)

tolanj
tolanj

Reputation: 3724

assuming ALL that comes out of the pipeline you posted is the directory name:

$target=/home/me/example
find . -name 'file.name' -print0 | 
xargs -0 grep -l "foo" | 
sed 's#\(.*\)/.*#\1#' | 
while read line #line is a variable with the contents of one line
do
    mv $line $target
done

Oh and get rid of the sort -u there is no need for it to move the directories and it 'serializes' your pipeline, you cant sort until the find is finished so the moves don't start, without it the moves can start as SOON as the 1st item is found.

Upvotes: 2

Ian Dickinson
Ian Dickinson

Reputation: 13305

The backtick operator evaluates a command and places the stdout as though you'd entered it on the command line. So, in your case:

mv `find . -name 'file.name' -print0 | xargs -0 grep -l "foo" | sed 's#\(.*\)/.*#\1#'` target

Upvotes: 0

Aaron Okano
Aaron Okano

Reputation: 2343

You can use xargs with substitution to get the desired effect:

commands to get directory list | xargs -i mv "{}" <destination>

Upvotes: 3

Related Questions