I am looking at writing a script that I can run from a cron job (say every month) that will copy my existing scripts to another folder, then in THAT new folder, append them all with the extension of .txt
I have the cp command down pat (cp /existing_folder /new_folder)
however I am stuck on the rename part.
All of the searching that I have found has examples of renaming files with an extension on them (rename file1.bak file2.txt)
what command can I use to rename all files in the new_folder that DO NOT have an extension on them to a file with the same file name but ending with .txt. I have files simply called news (no extension) and I am hoping to rename them (via a script) from news to news.txt
The reason for the renaming is to make it easier to share them via the web (for reading and editing off-site)
Some files have existing extensions (file.conf or file.sh) however the majority of my scripts do not have an extension on the end of the file....
I hope this makes sense - I have searched this pretty hard and tried many ideas, however nothing seems to work
Many thanks for taking the time to read my question
You can either use test or [ with an appropriate pattern to find out which files don't have a .txt extension, or you might use recent bash's extglob option to exploit the extended pattern matching.
for filename in test.sh test
do
basename=${filename%%.*}
extension=${filename#$basename}
newname=${basename}${extension:-.txt}
echo "$filename -> $newname"
done
This is one way to copy the files from one directory to another adding '.txt' as extension if file has no extension:
SOURCE_DIR="$HOME/tmp/dir1"
TARGET_DIR="$HOME/tmp/dir2"
for SF in $SOURCE_DIR/*
do
case `basename "$SF"` in
*.* )
# Has an extension
TF=$SF
;;
* )
# Does not have an extension
TF="$SF.txt"
;;
esac
cp $SOURCE_DIR/$SF $TARGET_DIR/$TF
if [[ $? -eq 0 ]]; then
echo "Successfully copied $SOURCE_DIR/$SF to $TARGET_DIR/$TF"
else
echo "$? : Error occured coping $SOURCE_DIR/$SF to $TARGET_DIR/$TF"
fi
done