0

This works for me:

$> find . -name "*.log" -exec basename '{}' \;
20160114.log
20160115.log
20160116.log
20160117.log
20160118.log
  1. Is the {}, \ and ';' mandatory when using -exec as any other syntax simply doesn't work?

  2. The following, more complex example doesn't work:

    $> find . -name "*.log" -exec echo $(basename '{}') \;
    ./log/20160114.log
    ./log/20160115.log
    ./log/20160116.log
    ./log/20160117.log
    ./log/20160118.log
    

    echo here is just to demonstrate. I eventually plan to use something like rm $TARGET_DIR/$(basename '{}') in its place… It just doesn't work that way (nesting). Any ideas?

msciwoj
  • 772
  • 7
  • 23
  • 1
    Regarding your first question, yes. The `{}` is replaced by the file name by `find`, the backslash is to escape the semi-colon which have a special meaning in shells, and the semi-colon tells `find` that the command has ended. – Some programmer dude Jan 19 '16 at 07:36
  • How about using `xargs`, e.g. `find . -name "*.log" | xargs basename` – mnille Jan 19 '16 at 07:39
  • @mnile, that works. I'm wondering here if there's a limitation of what can be put when using `-exec` format – msciwoj Jan 19 '16 at 08:11
  • @msciwoj, sorry, that I got your question wrong :-/ – mnille Jan 19 '16 at 08:38
  • @msciwoj The issue isn't the nesting, it's the order of operations. `$()` is executed first. And `basename {}` (without `find` to replace the `{}` first), probably just produced `{}`, so it would execute `echo {}` for each file. You can however have it execute in a subshell, by simply doing `find . -name "*.log" -exec bash -c 'echo "$(basename "$1")"' bash {} \;` Or choose some other construct – Reinstate Monica Please Jan 20 '16 at 02:55

0 Answers0