Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find -exec with multiple commands

Tags:

find

bash

I am trying to use find -exec with multiple commands without any success. Does anybody know if commands such as the following are possible?

find *.txt -exec echo "$(tail -1 '{}'),$(ls '{}')" \; 

Basically, I am trying to print the last line of each txt file in the current directory and print at the end of the line, a comma followed by the filename.

like image 958
Andy Avatar asked Feb 25 '11 16:02

Andy


People also ask

How do I run multiple commands in find?

Find exec multiple commands syntaxThe -exec flag to find causes find to execute the given command once per file matched, and it will place the name of the file wherever you put the {} placeholder. The command must end with a semicolon, which has to be escaped from the shell, either as \; or as " ; ".

How do you pipe multiple commands?

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 combine two commands in Linux?

Concatenate Commands With “&&“ The “&&” or AND operator executes the second command only if the preceding command succeeds.


2 Answers

find . -type d -exec sh -c "echo -n {}; echo -n ' x '; echo {}" \; 
like image 37
Avari Avatar answered Sep 20 '22 16:09

Avari


find accepts multiple -exec portions to the command. For example:

find . -name "*.txt" -exec echo {} \; -exec grep banana {} \; 

Note that in this case the second command will only run if the first one returns successfully, as mentioned by @Caleb. If you want both commands to run regardless of their success or failure, you could use this construct:

find . -name "*.txt" \( -exec echo {} \; -o -exec true \; \) -exec grep banana {} \; 
like image 131
Tinker Avatar answered Sep 21 '22 16:09

Tinker