I'm trying to find a Bourne shell script that will copy files from one directory using a wild card for the file name (*) and add some more characters in the middle of the file name as it is copied. As an example:
I've seen scripts where you can append characters to the end of a file or to the front of a file, but not in the middle of the file name. I was hoping for something as easy as:
You could use a for loop with parameter substitution:
#!/bin/bash
DT=$( date +"%Y%m%d" )
for file in /u01/tmp*.xml
do
fname="${file##*/}"
fname="${fname%.xml}"
fname="${fname}-${DT}.xml"
echo cp $file /u02/$fname
done
#!/bin/bash
DT=$( date +"%Y%m%d" )
for file in /u01/tmp*.xml
do
fname="${file##*/}"
fname="${fname%.xml}"
fname="${fname}-${DT}.xml"
echo cp $file /u02/$fname
done
Hello Yoda,
Could you please explain the code please it will be more useful for us.
DT=$( date +"%Y%m%d" )
# for each file in /u01/tmp*.xml
for file in /u01/tmp*.xml
do
# Remove every character before the last /
fname="${file##*/}"
# Remove .xml
fname="${fname%.xml}"
# Construct new file name
fname="${fname}-${DT}.xml"
echo cp $file /u02/$fname
done
This is great if I know what the suffix is. I was looking for more generality by being able to replace the wild card with some text and leave the rest of the file name as is. So let's call the new function cpr (copy with replace). With the same file set: