1

I'm currently trying to extract and use the filename of the result of a find command.

 find /var/log/*/* -iname "*.log" -type f -exec echo $(basename -- {}) \;

Actual Output:

/var/log/xyz/log1.log
/var/log/xyz/log2.log
/var/log/xyz/log3.log
/var/log/xyz/log4.log

Expected output:

log1.log
log2.log
log3.log
log4.log

Is there a trick or something that a misunderstand in using -exec ?

When I execute echo $(basename -- 'path/to/file.txt') in a bash it returns correctly file.txt

further details:

I need to use full path and basename in the result:

My full command looks like the following:

find /var/log/*/* -iname "*.log" -type f -exec gzip -k -f {} \; -exec gzip -t {}'.gz' \; -exec sh -c "cat {} | grep 'str' > /tmp/$(basename -- {})" \; # and more after

In this command, I can't extract the filename and use it. it always return the full path of the file like /var/log/foo/bar.log

Homer
  • 37
  • 11
  • 1
    Possible duplicate of [Have Find print just the filenames, not full paths](https://stackoverflow.com/questions/9202495/have-find-print-just-the-filenames-not-full-paths) – Ruslan Osmanov Oct 17 '19 at 09:20

3 Answers3

2

You don't need to call basename after exec option. Just use -execdir option and print {} as:

find /var/log/*/ -iname '*.log' -execdir printf '%s\n' {} +

If you really have to call basename then use it as:

find /var/log/*/ -iname '*.log' -exec basename -- {} \;

Based on your comments and edited question it seems you will be better off using find result this way:

while IFS= read -rd '' file; do
   echo "$file"
   basename "$file"
   # remaining commands like gzip etc
done < <(find /var/log/*/ -iname '*.log'  -print0)
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thanks for your response. It works, but I want to be able to use it in multiple `exec` I'v tryed your code but it didn't do the job :( I'v added further details in my question – Homer Oct 17 '19 at 09:38
  • 1
    Yeah ! It's works now ! Thanks a lot for your response ! I was strugling with this since yesterday evening ! – Homer Oct 17 '19 at 09:57
1

Could you please try following.

find /your/complete/path -type f -iname "*.log" -printf '%P\n'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • @RuslanOsmanov, Just checked attached link and seems `%P` option is not mentioned there, so added my answer here. – RavinderSingh13 Oct 17 '19 at 09:22
  • Thanks for you response, but I really need to use `-exec`. I'v added some further informations in my question in order to better explain what I'm tryin to achieve. – Homer Oct 17 '19 at 09:40
0

If you want to call basename then use it as:

find /var/log/\*/\* -iname "*.log" -type f -exec basename '{}' \;
Homer
  • 37
  • 11