Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux cp with a regexp

Tags:

regex

linux

cp

I would like to copy some files in a directory, renaming the files but conserving extension. Is this possible with a simple cp, using regex ?

For example :

cp ^myfile\.(.*) mydir/newname.$1

So I could copy the file conserving the extension but renaming it. Is there a way to get matched elements in the cp regex to use it in the command ? If not, I'll do a perl script I think, or if you have another way...

Thanks

like image 220
Johy Avatar asked Aug 20 '11 23:08

Johy


People also ask

Does CP use regex?

No. The cp command does not possess the capability to process any of its arguments as regular expressions. Even wildcards are not handled by it (or most executables); rather they are handled by the shell.

Can you use regex in Linux command line?

Regular expressions are special characters or sets of characters that help us to search for data and match the complex pattern. Regexps are most commonly used with the Linux commands:- grep, sed, tr, vi.

What is regex matching pattern?

A regex pattern matches a target string. The pattern is composed of a sequence of atoms. An atom is a single point within the regex pattern which it tries to match to the target string. The simplest atom is a literal, but grouping parts of the pattern to match an atom will require using ( ) as metacharacters.

What =~ in bash?

A regular expression matching sign, the =~ operator, is used to identify regular expressions. Perl has a similar operator for regular expression corresponding, which stimulated this operator.


2 Answers

Suppose you have myfile.a, myfile.b, myfile.c:

for i in myfile.*; do echo mv "$i" "${i/myfile./newname.}"; done

This creates (upon removal of echo) newname.a, newname.b, newname.c.

like image 173
Kerrek SB Avatar answered Sep 19 '22 21:09

Kerrek SB


The shell doesn't understand general regexes; you'll have to outsource to auxiliary programs for that. The classical scripty way to solve your task would be something like

for a in myfile.* ; do
  b=`echo $a | sed 's!^myfile!mydir/newname!'`
  cp $a $b
done

Or have a perl script generate a list of commands that you then source into the shell.

like image 21
hmakholm left over Monica Avatar answered Sep 22 '22 21:09

hmakholm left over Monica