Reputation: 252
I have a relatively large amount of files inside a certain directory. There are always 4 types of files and each file type is numbered like so:
FileType<1-4>_<0000-9999>.ext
So, in the worst case I´d have 40000 files. Now, Im trying to write a simple bash script that filters out all files which are not contained in a range defined by user input, like for instance:
$ ./FilterScript 0 10
Which should output a list of all of the 4 filetypes going from the 0000 to the 0010. I have been working with grep and regexp and gotten some success. This is the example command I´m using to filter everything out (outputs from 0012 to 0023):
ls *.ext | grep -E '00[1][2-8]|00[2][0-3]'
Now the question is, how can I translate the user input to the script into the corresponding regexp expression, without manipulating the input variables as strings? If I want for example the range 90-120, the regexp expresion changes. Is this possible? I have tried using do loops, but in general I think the above mentioned command has a better performance.
Thanks in advance! Ch.
Upvotes: 1
Views: 60
Reputation: 204015
Regarding ls *.ext | ...
- don't do that, see https://mywiki.wooledge.org/ParsingLs.
Regarding using a regexp to match a range of numbers - don't do that, use a numeric comparison.
It sounds like you should be doing something like the following using any awk:
#!/usr/bin/env bash
awk -v beg="$1" -v end="$2" '
BEGIN {
for ( i=1; i<ARGC; i++) {
n = split(ARGV[i],parts,/[_.]/)
num = parts[n-1] + 0
if ( (beg <= num) && (num <= end) ) {
print ARGV[i]
}
}
exit
}
' ./*.ext
The above is obviously untested since you didn't provide any sample input/output for us to test a potential solution with.
Upvotes: 1