Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash One Liner: copy template_*.txt to foo_*.txt?

Tags:

bash

Say I have three files (template_*.txt):

  • template_x.txt
  • template_y.txt
  • template_z.txt

I want to copy them to three new files (foo_*.txt).

  • foo_x.txt
  • foo_y.txt
  • foo_z.txt

Is there some simple way to do that with one command, e.g.

cp --enableAwesomeness template_*.txt foo_*.txt

like image 456
Patrick McElhaney Avatar asked Aug 25 '08 17:08

Patrick McElhaney


5 Answers

for f in template_*.txt; do cp $f foo_${f#template_}; done
like image 180
Chris Conway Avatar answered Nov 09 '22 10:11

Chris Conway


[01:22 PM] matt@Lunchbox:~/tmp/ba$
ls
template_x.txt  template_y.txt  template_z.txt

[01:22 PM] matt@Lunchbox:~/tmp/ba$
for i in template_*.txt ; do mv $i foo${i:8}; done

[01:22 PM] matt@Lunchbox:~/tmp/ba$
ls
foo_x.txt  foo_y.txt  foo_z.txt
like image 20
Matt McMinn Avatar answered Nov 09 '22 10:11

Matt McMinn


My preferred way:

for f in template_*.txt
do
  cp $f ${f/template/foo}
done

The "I-don't-remember-the-substitution-syntax" way:

for i in x y z
do
  cp template_$i foo_$
done
like image 35
Roberto Bonvallet Avatar answered Nov 09 '22 12:11

Roberto Bonvallet


This should work:

for file in template_*.txt ; do cp $file `echo $file | sed 's/template_\(.*\)/foo_\1/'` ; done
like image 2
Chris Bartow Avatar answered Nov 09 '22 10:11

Chris Bartow


for i in template_*.txt; do cp -v "$i" "`echo $i | sed 's%^template_%foo_%'`"; done

Probably breaks if your filenames have funky characters in them. Remove the '-v' when (if) you get confidence that it works reliably.

like image 1
pauldoo Avatar answered Nov 09 '22 11:11

pauldoo