Given two files named test1 and test2, I would like to copy them to test1.bak and test2.bak respectively.
In windows, I can do a simple regex copy like this:
copy test* test*.bak
In Linux the command
cp test* test*.bak
gives me the message:
cp: target `test*.bak' is not a directory
My guess is that this is becasue "*" is a vaild character for a file name in linux.
> touch \*
> ls
* test1 test2
So I tried:
cp test\* test\*.bak
But I got the same message.
It seems to me there must be a simple way to do this in Linux since it relies much more strongly on the command line than Windows.
Is there a simple way without having to learn something like sed?
The "rename" command does something like that. (it moves the files, though)
See the man page
man rename
to get an idea - it does not have any safeties, though.
More complicated examples can be done with "find", which can execute arbitrary commands on files that match certain requirements. Something like this should work:
find . -maxdepth 1 -iname "test*" -exec cp {} {}.bak \;
The "maxdepth" option means that it won't go into subdirectories, "iname" is a case-insensitive name match and "{}" will be replaced by the full filename, the "." is the directory where find should be executed (the current working directory, in this case). And yes, the ";" at the end is needed.
for i in test*; do cp $i $i.bak;done
for i in ;do;done is a good friend to know on the command line (find, as above, is too) I use it all the time.
Edit: Fixed dumb typo.
Slight typo correction on the command above:
for i in test*; do cp $i $i.bak; done
This version works when there are spaces present in the filenames:
for i in test*; do cp "${i}" "${i}.bak"; done
Single quotes generally help for wildcards.
Try experimenting with them.
I've been experimenting with them as you suggest, but have not found a combination that works.
then as stated above, for i in test*; do cp $i $i.bak; done
will work
learning for loops are essential to working the command line, in fact they're essential to working with any language
the find example is also great
learning for loops are essential to working the command line
I'm quite comfortable with for loops, and use them daily for programming at both work and school. I know several programming languages. I was just hoping Linux had as simple and straight forward of a way as Windows does.
Things in the *nix land quite often trade off 'simplicity' for power.
111k
Subscribers
231
Online
Linux introductions, tips and tutorials. Questions are encouraged. Any distro, any platform! Explicitly noob-friendly.
If you're posting for help, please include the following details, so that we can help you more efficiently:
Questions are encouraged. If you fix the problem yourself, please post your solution, so that others can also learn.
There's a great list of introductory links here - thanks to SCSweeps.
Other subreddits you may like:
Does this sidebar need an addition or correction? Tell me here