LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Copy and Renaming files (https://www.linuxquestions.org/questions/linux-newbie-8/copy-and-renaming-files-790652/)

akareh 02-21-2010 08:01 PM

Copy and Renaming files
 
Hi there :)

I'm quite new to Linux and bash scripting, and I've hit a roadblock in a script I'm writing. At the moment I have it so that a user can enter a file path and the name of an editor, like pico, and it will automatically bring up their file for them to edit. I am trying to figure out how to add code to this so that the file will be copied before any edits and saved as a separate file from the main file. I don't know how to copy the contents of a file, or a file before it's been edited, and I don't know how to write code to automatically generate a name for the previous versions of the file.

Below is the code that I have written so far:
Code:

echo "Please Enter a Text Editor: "
read TEXT_EDITOR
echo "Please Enter a Filepath: "
read FILEPATH
echo ""
if [ -e $FILEPATH ]
  then
    $TEXT_EDITOR $FILEPATH
else
    echo "That is not a valid filepath or editor."
fi

Basically, I am aiming to have a directory with the main version of a file, eg, Story.txt, alongside the previous versions of it, eg Story_a.txt, Story_b.txt, etc.

Any help would be greatly appreciated :)

evo2 02-21-2010 09:18 PM

How about:
Code:

#!/bin/bash
echo "Please Enter a Text Editor: "
read TEXT_EDITOR
echo "Please Enter a Filepath: "
read FILEPATH
echo ""
if [ -e $FILEPATH ]
  then
    NEWFILE="${FILEPATH%*.[^.]}_a${FILEPATH/*./}"
    cp "$FILEPATH" "$NEWFILE"
    $TEXT_EDITOR $NEWFILE
else
    echo "That is not a valid filepath or editor."
fi

Generating the name of the new file could be done a bit more simply, but this should work even in the case where the file name contains multiple '.'s. This script does *not* check that the '_a' version of the file already exists.

Evo2.


All times are GMT -5. The time now is 05:09 PM.