简体   繁体   中英

'find' all .log files under a directory, copy them to another directory named after their parent directory?

Random eg:

/stack-exchange/
|
|-- stack-overflow/
|   |-- questions/
|   |-- people/
|   |-- site.log
|-- super-user/
|   |-- questions/
|   |-- people/
|   |-- answers.log
|-- ask-ubuntu/
|   |-- questions/
|   |-- people/
|   |-- linux.log
|-- logs/

This is the command I'd use to find all log files in a given directory:

find /stack-exchange/ -type f -name "*.log"

Now, going by the example, I'd like to copy all 3 log files (site.log, answers.log & linux.log) to /stack-exchange/logs directory and have them named after their parent directory, like so:

/stack-exchange/
|
|-- [...]
|
|-- logs/
|   |-- stack-overflow.log
|   |-- super-user.log
|   |-- ask-ubuntu.log

How do I do that? I've tried this:

find /stack-exchange/ -type f -iname "*.log" -exec cp "{}" "../logs/$(basename "$(dirname "{}")").log" \;

I think I am close, but it doesn't work. All it does is create a ..log file. What am I doing wrong, and how do I fix it?

Based on this answer to the question Use current filename ("{}") multiple times in "find -exec"? , this works:

find /stack-exchange/ -type f -iname "*.log" -exec sh -c 'cp "$0" "./logs/$(basename "$(dirname "$0")").log"' {} \;

Thank you @rdupz ( see comment ), for pointing me in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM