tags:

views:

51

answers:

3

Hi

with linux bash shell , how can i use regex to get a certain string of a file

by example:

for filename *.tgz do

"get the certain string of filename (in my case, get 2010.04.12 of file 2010.01.12myfile.tgz)"

done

or should I turn to perl

Merci

frank

+1  A: 

with bash, for the simplest case, if you know what you want to get is a date stamp, you can just use shell expansion

#!/bin/bash

for file in 20[0-9][0-9].[01][0-9].[0-9][0-9]*tgz
do
 echo $file
done

else, if its anything before the first alphabet,

for file in *tgz
do
 echo ${file%%[a-zA-Z]*}
done

otherwise, you should spell out your criteria for the search.

ghostdog74
sorry to my bad expression, i mean to get the string that i want not the file . the shell is like this: for filename *.tgzdo #get the certain string of filename (in my case, get 2010.04.12 of file 2010.01.12myfile.tgz)done
chun
A: 
#!/bin/sh
a="2010.04.18Myfile.tgz"
echo ${a%%+([a-zA-Z.])}

bash' regexp are quite powerful (at least compared to standard sh or command.com :-))

Patrick
hi, can't get this donei just want to sign '2010.04.18' to a variable
chun
you can say b=${a%%...} as in the example above
Patrick
You would need to set your shebang to `#!/bin/bash` and have `shopt extglob` in order to use `+(...)`.
Dennis Williamson
Dennis, thanks for the correction! My mistake.
Patrick
+1  A: 
FILE=2010.01.12myfile.tgz

echo ${FILE:0:10}

gives

2010.01.12
fpmurphy
I guess he needs d=${FILE:0:10}
user unknown
that's what i did yesterday finally, but thanks all the same~~
chun