user3761584
user3761584

Reputation: 3

In unix , moving a file with xargs after finding and zipping it?

So in a bashscript i've the following very simple line , but how can i chain it further to move the file ?

find . -type f -ctime -$2 -name "mylog*.log" | xargs bzip2

This works fine but i'd also like to move the file to a new directory once I am done with the bzip2.

Upvotes: 0

Views: 174

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

One standard trick is to use a new script that does whatever you need. Here, I assume that ${OTHER_DIRECTORY} is an environment variable that says where to put the compressed files, but there are plenty of other (better!) ways to get that information to the script (such as specifying the directory as the first argument — as the last argument is a bad idea).

#!/bin/bash

for file in "$@"
do
    bzip2 "$file"
    mv "$file.bz2" "${OTHER_DIRECTORY:-/tmp}"
done

You then run that script with find:

find . -type f ctime -$2 -name "mylog*.log" -exec tinyscript.sh {} +

This is pretty effective. If you only want one mv command, you can consider something along the lines of:

bzip2 "$@"
bz2=()
for file in "$@"; do bz2+=( "$file.bz2" ) done
mv "${bz3[@]}" "${OTHER_DIRECTORY:-/tmp}"

This code works even if the path names contain spaces and other untoward characters.

Upvotes: 1

user3553031
user3553031

Reputation: 6214

One option might be something like this:

find . -type f -ctime -$2 -name "mylog*.log" -exec bzip2 {} \; -exec mv {} /path/to/new_dir/ \; 

Upvotes: 1

Related Questions