Friday, May 3, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 624  / 2 Years ago, mon, may 9, 2022, 7:27:26

I'm trying to rename every access.log.gz file (note: exact filename, not "beginning with" or "containing") found in /home/*/logs to date-access.log.gz in the same folder.



for file in /home/*/logs/access.log.gz
do
mv -v "$file" /home/*/logs/old/`date +%G-%m-%d`"-access.log.gz"
done


Of course I'm getting /home/*/logs/2014-09-08-access.log.gz - No such file or directory. How can I call the * paths back? Each file should be renamed and moved to /old/ subdir of the source folder. I tried with



mv -v "$file" /home/`$1`/logs/old/`date +%G-%m-%d`"-access.log.gz"


... but didn't work.


More From » bash

 Answers
1

Use find (How can I use find command more efficiently?).



find /home/ -ipath */logs/access.log.gz


That should find all the files you're interested in, and print them. You could plug that into your script, but it's probably easier to let find do all the hard work.



find /home/ -ipath */logs/access.log.gz -execdir mv "{}" "old/`date +%G-%m-%d`-access.log.gz" ;


The features of find we're using here are:




  • -ipath matches patterns in the found filenames. You could also use -name if you knew for sure there's only one access.log.gz file in each subpath (-name access.log.gz).

  • -execdir executes the given command on each found file, from the subdirectory containing the matched file. This is equivalent to doing cd to where each file is and then running the command there. In this case it saves a lot of path manipulation logic. The found file is substituted for {}. Notice also that "old" is given as a relative path (as you said that old/ exists in logs/)


[#23287] Monday, May 9, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
whipstder

Total Points: 189
Total Questions: 110
Total Answers: 99

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
;