Avatar of SWB-Consulting
SWB-Consulting
 asked on

Copy files of a certain pattern and add prefix

On linux:

I have the following files:

popups.csv
search.csv
bla.popups.csv
bla.search.csv

I want to copy popups.csv and search.csv and prepend xyz so that after executing my command I have:

popups.csv
search.csv
bla.popups.csv
bla.search.csv
xyz.popups.csv
xyz.search.csv

What's the command I'm looking for?
Shell ScriptingUnix OSLinux

Avatar of undefined
Last Comment
Steven Vona

8/22/2022 - Mon
woolmilkporc

One line?

for file in popups.csv search.csv; do cp -p $file xyz.$file;  done

Two commands?

cp -p popups.csv xyz.popups.csv
cp -p search.csv xyz.search.csv

The "-p" flag of "cp" preserves the timestamps. Omit it if you want to create the new files using the current time.
SWB-Consulting

ASKER
Thanks, I would like a command that doesn't have to hardcode the filenames through. Basically take any file hat ends in csv and doesn't already have a prefix and copy it into filename with specified prefix.

In reality I have many more filenames sitting in there and I just wanted to simplify for this example.
woolmilkporc

That's what I'd like to call over-simplifying.

Here you go, for always "xyz" (I don't assume that's what you're after, but anyway):

for file in $(ls *.csv); do if [[ "${file#xyz.}" == "$file" ]]; then echo cp -p $file xyz.$file; fi; done

echo is for testing, remove it to actually run the displayed commands.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
woolmilkporc

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
SOLUTION
Steven Vona

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.