Hekri
Hekri

Reputation: 33

xargs pipes with multiple commands

I am trying to find all files older than 30 days with type .pkl in a directory, get the parent directory of found files and remove them. My solution looks something like this:

find path_to_dir/.cache -type f -name "*.pkl" -mtime +30 |
  xargs dirname | xargs rm -r

Is there a way to avoid the double xargs? Also, a further task of mine would be to delete all log files, but not parent directory. i.e.

find path_to_dir -type f -name "*.log" -mtime +30 -delete

Could I do above in one line without code replication?

Upvotes: 0

Views: 183

Answers (1)

larsks
larsks

Reputation: 311506

If you're using GNU find, you can use the %h token in the -printf command:

find path_to_dir/.cache -type f -name '*.pkl' -mtime +30 -printf '%h\0' |
  xargs -0 rm -r

For combining the two operations, something like this might work:

find path_to_dir/ -mtime +30 -type f \( -name '*.pkl' -printf '%h\0' -o -name '*.log' -print0 \) |
  xargs -0 rm -r

...but that assumes that you can use the same starting prefix for both operations (in your example, you're using path_to_dir/.cache in the first case and path_to_dir in the second case).

Upvotes: 1

Related Questions