Category Archives: bash

Removing all files older then X days

Log files and output files are automatically generated by applications continuesly. So you will likely have thousands after a few days or weeks of operation. There are multiple ways to remove these older files, but we will demonstrate a simple bash command of

find ./* -mtime +<days> -exec rm {} \;

# Remove files older then 30 days

find ./* -mtime +30 -exec rm {} \;
# Remove files older then 7 days

find ./* -mtime +7 -exec rm {} \;
# Remove files older then 1 hour

find ./* -mtime +1/24 -exec rm {} \;

Tagging file names in UNIX or Linux

File names can be used to identify what is in the file, the date of changes , the classification of data, or the type of data contained with in. There are times when you will have hundreds if not thousands of files contained the same type or classification of data and you want to bulk process this information. One way of accomplishing this task is through file names of a certain format. Here we will demonstrate changing all the files contained inside a single directory with an ending of ‘renamed’ where the file begins with an f.

First create a test directory and place 6 files three beginning with t and three beginning with f.

[larry@localhost ~]$ mkdir test
[larry@localhost ~]$ cd test
[larry@localhost test]$ touch t1
[larry@localhost test]$ touch t2
[larry@localhost test]$ touch t3
[larry@localhost test]$ touch f1
[larry@localhost test]$ touch f2
[larry@localhost test]$ touch f3
[larry@localhost test]$ ls 
f1  f2  f3  t1  t2  t3
[larry@localhost test]$ 

We want to change all the files starting with f to an ending of renamed. we will use the following bash command to perform this action.

find . -type f -name 'f*' -print0 | xargs --null -I{} mv {} {}_renamed
[larry@localhost test]$ find . -type f -name 'f*' -print0 | xargs --null -I{} mv {} {}_renamed
[larry@localhost test]$ ls
f1_renamed  f2_renamed  f3_renamed  t1  t2  t3
[larry@localhost test]$ 

You can now see that all files that begain with an ‘f’ now have the end of ‘renamed’