Reputation: 3628
I have got a directory containing files of type *.cpp
.So i would like to copy each file in the directory and to paste it in the same directory by using
cp -a *.cpp
with an option to remove the .cpp while pasting. Is it possible?
Upvotes: 3
Views: 4230
Reputation: 136
If you know the file extension to remove (as in your case), you can use basename
strip the extension one-by-one:
for i in *.cpp; do cp $i $(basename $i .cpp); done
This approach works based on the final file extension of the files, and it continues to work just fine when files have more than one extension (before the one you wish to remove).
Upvotes: 0
Reputation: 200
Can use rename, optionally with -f to force rewrite existing files.
rename -f 's/\.ext$//' *.ext
To preview actions, but don't change files, use -n switch (No action).
This is not copy but move :-(
Upvotes: 1
Reputation: 1963
You can do this just by means of bash parameter extension, as mentioned in the bash manual:
${parameter%%word} Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted.
...
for i in *.cpp
do
cp -a $i ${i%%.cpp}
done
Upvotes: 6
Reputation: 2789
Here is a simple bash script. This script assumes that the file name only contains one "." character and splits based on that.
#!/bin/sh
for f in *.cpp; do
#This line splits the file name on the delimiter "."
baseName=`echo $f | cut -d "." -f 1`
newExtension=".new"
cp $f $baseName$newExtension
done
Upvotes: 6