I would like to recursively go through all subdirectories and remove the oldest two PDFs in each subfolder named "bak":
Works:
find . -type d -name "bak" \
-exec bash -c "cd '{}' && pwd" \;
Does not work, as the double quotes are already in use:
find . -type d -name "bak" \
-exec bash -c "cd '{}' && rm "$(ls -t *.pdf | tail -2)"" \;
Any solution to the double quote conundrum?
In a double quoted string you can use backslashes to escape other double quotes, e.g.
find ... "rm \"\$(...)\""
If that is too convoluted use variables:
cmd='$(...)'
find ... "rm $cmd"
However, I think your find -exec
has more problems than that.
{}
inside the command string "cd '{}' ..."
is risky. If there is a '
inside the file name things will break and might execcute unexpected commands.$()
will be expanded by bash before find
even runs. So ls -t *.pdf | tail -2
will only be executed once in the top directory .
instead of once for each found directory. rm
will (try to) delete the same file for each found directory.rm "$(ls -t *.pdf | tail -2)"
will not work if ls
lists more than one file. Because of the quotes both files would be listed in one argument. Therefore, rm
would try to delete one file with the name first.pdf\nsecond.pdf
.I'd suggest
cmd='cd "$1" && ls -t *.pdf | tail -n2 | sed "s/./\\\\&/g" | xargs rm'
find . -type d -name bak -exec bash -c "$cmd" -- {} \;