开发者

How to rename files keeping a variable part of the original file name

I'm 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 two digits? 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


Would something like this help?

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

Bash Shell Parameter Expansion


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).


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜