Loop through Apache 2 log file names and compare numbers with linux bash

Here is an example of the logs in the / var / www / apache 2 / log folder -

./no_domain_access.log.7.gz
./no_domain_access.log.8.gz
./no_domain_access.log.9.gz
./no_domain_error.log.10.gz
./no_domain_error.log.11.gz
./no_domain_error.log.12.gz
./no_domain_error.log.13.gz
./no_domain_error.log.14.gz
./no_domain_error.log.15.gz
./no_domain_error.log.16.gz
./no_domain_error.log.17.gz
./no_domain_error.log.18.gz
./no_domain_error.log.19.gz
./no_domain_error.log.20.gz

and up to 50 ...

I would like to iterate over these files and delete all log files that are greater than 5.

using regex syntax will give me the opportunity to match the numbers in the pattern [1-9] or {1,2}, but it will also correspond to those log files that I do not want to delete (single numbers 1-5 log files that I want to save )

How can I match only file names with numbers above 5?

Thank!

+4
source share
4 answers

You can use a awksingle line for this :

printf '%s\n' *[0-9].gz | awk -F '.' '$(NF-1) >= 5'

awk $(NF-1) ( ) 5.

:

printf '%s\n' *[0-9].gz | awk -F '.' '$(NF-1) >= 5' | xargs rm

xargs awk rm, .

+2

bash, regex ~, , , 5

for file in /var/www/apache2/log/*.gz; do 
    test -f "$file" || continue
    [[ $file =~ ^.*log\.([[:digit:]]+).*$ ]] && { (( "${BASH_REMATCH[1]}" > 5  )) && printf "%s\n" "$file"; } 
done

, printf "%s\n" rm.

+1

find . -regex './no_domain_access.log.*gz' ! -regex './no_domain_access.log.[1-5].gz'

, no_domain..., , 1 5.

0

, shell globs POSIX:

rm -f no_domain_access.log.[6-9].gz no_domain_access.log.[0-9][0-9].gz

bash:

rm -f no_domain_access.log.{6..50}.gz

Perhaps they were created using logrotate or a similar rotation log utility .
You can simply change your configuration to store only five logs.

If it is managed by logrotate, you can find the documentation with man logrotate, and you will probably find something like this:

/var/log/no_domain_access.log {
    rotate 50
    daily
}

Change 50to 5, and you're done. You probably (?) Still need to clear current old logs using one of the commands above.

0
source

Source: https://habr.com/ru/post/1685866/


All Articles