Linux cp with a regexp
Solution 1
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
.
Solution 2
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.
Johy
I work on PubMed at NCBI/NLM/NIH. I specialize in text mining, particularly biomedical information retrieval. I'm fascinated with Web technologies in general. I am also a guitarist, a dad, a cheese addict and I love cartoons.
Updated on June 09, 2022Comments
-
Johy about 2 years
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
-
Kerrek SB almost 13 yearsDoes the new name somehow derive from the old name? Can you say the concrete situation, maybe it can be done with simple shell substitution.
-
Johy almost 13 yearsSure. The new name doesn't have a link with the old... A real example : cp treepict_313* dir/foobar.$1 foobar is a name given by a website user, it can be anything then. I just rename the file with the desired name before the user download it... To not let a formatted name as treepict_300.ext... Is this clearer ?
-
Ray Toal almost 13 yearsOr maybe you want to rename
a.c
,a.s
,a.o
,a.h
anda.bak
tob.c
,b.s
,b.o
,b.h
andb.bak
? -
Johy almost 13 yearsThat's it, but copying it in another directory in the same time (i mean, keeping a.c, a.s, a.o, a.h and a.bak)
-
-
Kerrek SB almost 13 years@Ray: Substitution solves 90% of my file handling needs and is the prime reason for having a Bash in Windows! :-)