tags:

views:

53

answers:

4

Im trying to make a script that will go into a directory and run my own application with each file matching a regular expression, specifically "Test[0-9]*.txt".

My input filenames look like this "TestXX.txt". Now, I could just use cut and chop off the Test and .txt, but how would I do this if XX wasn't predefined to be 2 numbers? What would I do if i had "Test1.txt" ... "Test10.txt"? In other words, How would I get the [0-9]* part?

Just so you know, I want to be able to make a OutputXX.txt :)

EDIT:

I have files with filename "Test[0-9]*.txt" and I want to manipulate the string into "Output[0-9]*.txt"

+1  A: 

Hi,

You need to use rounded brackets around the part you want to keep.

i.e. "Test([0-9]*).txt"

The syntax for replacing these bracketed groups varies between programs, but you'll probably find you can use \1 , something like this:

s/Test(0-9*).txt/Output\1.txt/

If you're using a unix shell, then 'sed' might be your best bet for performing the transformation.

http://www.grymoire.com/Unix/Sed.html#uh-4

Hope that helps

amir75
Looks sweet to bad I can't set two answers. One is simple and the other more extendable >.> gay
Buttink
+1  A: 

Would something like this help?

#!/bin/bash
for f in Test*.txt ;
do
    process < $f > ${f/Test/Output}
done

Bash Shell Parameter Expansion

Keith
This worked! Im stupid and am still trying to figure out how to make my process run but thats another matter.
Buttink
@keith, this worked but it works for all cases, not just numbers.. do you intend to process `TestABC.txt` as well?
ghostdog74
+2  A: 

A good tutorial on regexes in bash is here. Summarizing, you need something like:

if [[$filenamein =~ "^Test([0-9]*).txt$"]]; then
  filenameout = "Output${BASH_REMATCH[1]}.txt"

and so on. The key is that, when you perform the =~" regex-match, the "sub-matches" to parentheses-enclosed groups in the RE are set in the entries of arrayBASH_REMATCH(the[0]entry is the whole match,1` the first parentheses-enclosed group, etc).

Alex Martelli
A: 
for file in Test[0-9]*.txt;
do
 num=${file//[^0-9]/}
 process $file > "Output${num}.txt"
done
ghostdog74