Script for renaming multiple scripts

Hi There

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.

Posix shell, ksh, bash:

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

Many thanks for your replies

I have tried "spacebars" script however it is giving out the following error:

I have set the following parameters:

SOURCE_DIR="/home/irlp/webstuff"
TARGET_DIR="/home/irlp/webstuff/trial"

It appears that the script is not copying the files over and appending the .txt extension on the newly copied files into the target directory

Am I on the right path with this or something astray?

Change the first 4 lines to this:

SOURCE_DIR="/home/irlp/webstuff"
TARGET_DIR="/home/irlp/webstuff/trial"
cd $SOURCE_DIR

for SF in *

Many thanks for the help. All sorted now :slight_smile: