Friday, October 7, 2022

[SOLVED] GREP a range of files with a numeric filename

Issue

I have files that are located in a temp folder that I need to move to another folder, the files are named in sequence as so:

1_492724_860619121.dbf.gz
1_492725_860619121.dbf.gz
1_492726_860619121.dbf.gz
...
1_493069_860619121.dbf.gz

I used to move these files monthly so I used grep on the month in question :

for i in `ls -ltr | grep Jul|awk '{print $9}'`; do mv $i JulFolder; done

Now I only want to move a range of files based on their name :
from 1_492724_860619121.dbf.gz to 1_493053_860619121.dbf.gz

What is the correct use the of combination of grep and awk to select the desired files ?

Note that awk '{print $9}' is used to select the right column containing the files' name from ls -ltr.


Solution

You can try below. (change FROM and TO as you want)

for i in `ls -1|awk -F_ '{if($2 >= FROM && $2 <= TO) print $0}' FROM=492724 TO=493053`
do 
    mv $i toFolder
done


Answered By - ryuken73
Answer Checked By - David Marino (WPSolving Volunteer)