How to use `-exec` with multiple commands?

To use -exec with multiple commands in the find command, you can use a shell to execute the commands together. This is typically done by invoking a shell with the -exec option and using a command separator like ; or &&.

Here’s how you can do it:

Using sh -c

You can use sh -c to run multiple commands. Here’s an example:

find /path/to/search -type f -name "*.txt" -exec sh -c 'cat {} && echo "Processed: {}"' \;

In this example:

  • sh -c starts a new shell.
  • The commands inside the single quotes are executed in that shell.
  • {} is replaced with the current file found by find.
  • && is used to run the second command only if the first command (cat {}) succeeds.

Using ; to Separate Commands

If you want to run multiple commands regardless of the success of the previous command, you can separate them with a semicolon:

find /path/to/search -type f -name "*.txt" -exec sh -c 'cat {}; echo "Processed: {}"' \;

Important Note

When using sh -c, you need to ensure that the {} placeholder is correctly referenced within the command string. If you want to use {} multiple times in the command, you can pass it as an argument:

find /path/to/search -type f -name "*.txt" -exec sh -c 'for file; do cat "$file"; echo "Processed: $file"; done' _ {} +

In this case, the _ is a placeholder for $0, and {} is passed as arguments to the shell script. The + at the end allows find to pass multiple files at once, which can be more efficient than using \;.

0 Comments

no data
Be the first to share your comment!