Re: Multiple files
On 31 May 2002, Daniel D Jones wrote:
> How does one handle multiple files via most command line utilities? For
> example, suppose you have a handful of perl scripts (*.pl) and you want
> to save them in the same directory with a different extension. The
> command
>
> cp *.pl *.bak
>
> complains that you're copying multiple files but the last command isn't
> a directory.
That's right. Say you have a directory that looks like this:
$ ls
bar.pl baz.pl foo.pl
Then, by shell globbing, `cp *.pl *.bak` expands to:
`cp bar.pl baz.pl foo.pl` which would be copying two files into one
non-directory. Obviously, incorrect.
> Or suppose you have a series of perl scripts which are saved in DOS
> line-end format. The extra ^M on the bang line causes bash not to
> recognize the path to perl, and the script to fail. Sounds like a job
> for sed.
>
> sed s/^M// *.pl > *.unix
sed doesn't QUITE work that way. And you have that same problem
with globbing.
> Again, the file naming criteria doesn't work. I could write a script
> which essentially generates a new command for each file fitting the
> naming pattern, or perhaps use find -exec but there's got to be a
> straightforward way to do this on the command line. Doesn't there?
The most straight-forward and portable Bourne way of doing this
is with a loop:
$ for i in *.pl; do cp $i `echo $i | sed -e 's/\.pl$/\.bak/'`; done
So let's dissect this:
for i in *.pl; do ...; done
Iterate over all the *.pl files in the directory, and use $i
as the counter variable.
cp $i `...`
Copy the file in counter $i to the name returned by the
commands executed in `...` on stdout.
echo $i | sed -e 's/\.pl$/\.bak/'
Replace the .pl extension at the end of $i with .bak
Now, if you use GNU bash as your shell, you can simplify the
command by avoiding sed, and using the built-in pattern matching:
$ for i in *.pl; do cp $i ${i%.pl}.bak; done
Simon
--
To UNSUBSCRIBE, email to debian-user-request@lists.debian.org
with a subject of "unsubscribe". Trouble? Contact listmaster@lists.debian.org
Reply to: