Operating System - HP-UX
1820390 Members
3954 Online
109623 Solutions
New Discussion юеВ

cp command with regular expressions

 
SOLVED
Go to solution
Danny Fang
Frequent Advisor

cp command with regular expressions

Hi,

I have files with the following naming format:
measlog0, measlog2, measlog3, measlog4, measlog5, measlog6, measlog7, measlog8, measlog9, measlog10, measlog11.

I'd like to copy these files to different directory, using "cp" command with some regular expressions:

1) cp measlog[0-9]* /tmp/testdir
This option works well if there no other characters after the filename measlog such as measlog9abc or measlog9_test

I attempted a more secure method, but did not work:
bash-2.05$ cp measlog[0-9]*$ /tmp/testdir
cp: cannot access measlog[0-9]*$

bash-2.05$ cp measlog[0-9]{2} /tmp/testdir
cp: cannot access measlog[0-9]{2}

Could anyone show how I could use a more "secure" regular expression within "cp" to ensure files like measlog0, measlog1 ... measlog11 (i.e. measlog) are the only files copied over?

Thanks
Danny
7 REPLIES 7
Piergiacomo Perini
Trusted Contributor

Re: cp command with regular expressions

Hi Danny,

and this :

cp measlog?? /tmp/testdir

could meet your needs?

hth
regards
pg
Peter Godron
Honored Contributor
Solution

Re: cp command with regular expressions

Danny,
cp measlog*[0-9] /tmp/testdir
Piergiacomo Perini
Trusted Contributor

Re: cp command with regular expressions

Hi again Danny,

or try

cp measlog[0-90-9] /tmp/testdir

Regards
pg
Yang Qin_1
Honored Contributor

Re: cp command with regular expressions

Hi, Danny,

Try:
for fn in measlog*
do cp $fn /tmp/testdir
done

Regards,
Yang
Bill Hassell
Honored Contributor

Re: cp command with regular expressions

Since there are two different forms of the filename, you have to use two expressions like this:

cp measlog[0-9] measlog[0-9][0-9] /somedir

As always, test the list with echo first:

echo cp measlog[0-9] measlog[0-9][0-9] /somedir

cp knows nothing about regular expresions (or more accurately, filename generation) so the echo will show you what cp will see.


Bill Hassell, sysadmin
Peter Godron
Honored Contributor

Re: cp command with regular expressions

Danny,
can you please update with any feedback.

If the problem is resolved, could you please identify the solution, rewards any helpful answers and close the thread.
Danny Fang
Frequent Advisor

Re: cp command with regular expressions

Hi everyone,
Issue resolved by using the method suggested by Peter, i.e.:
cp measlog*[0-9] /tmp/testdir

Thank you all for your help.