1

how can I do this:

I have a file, eval.txt saved into a variable, that I want to rename timestamp_eval.txt

filetosend=/home/cft/eval.txt
filename=$(echo $filetosend | cut -d '/' -f4) //to get only the name
DATE=$(date +%Y%m%d)
filename=${DATE}_${filename} //add timestamp to name

how can I rename $filetosend ?

I found this solution:

DATE=(date +%Y%m%d)
mydir=$(echo $(dirname $a))
myfile=$(echo $(basename $a))
myfile=${DATE}_${myfile}
filetosend=$mydir/$myfile
cp $a $filetosend
rschirin
  • 1,939
  • 10
  • 34
  • 44

3 Answers3

1

Try doing this if you really need a variable :

filetosend=/home/cft/eval.txt
cd "${filetosend%/*}"
filename="${filetosend##*/}"
DATE=$(date "+%Y%m%d")
filename="${DATE}_$filename"
mv "$filetosend" "$filename"

If you don't really need a variable using rename :

rename "s|[^/]+$|$(date +%Y%m%d)_$&|" /home/cft/eval.txt

or decomposed on multi-lines :

cd /home/cft/
rename "s/.*/$(date "+%Y%m%d")_$&/" eval.txt
rename "s|[^/]+$|$(date "+%Y%m%d")_$&|"

Note

Read this post to know if you have the good rename on your system + extra explanations.

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

The simplest way would be to do:

mv /home/cft/eval.txt /home/cft/$(date "+%Y%m%d")_eval.txt
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
  • Hi sudo_O, Read again the title sudo_O : "Bash how can rename a file saved into a **variable**?" =) – Gilles Quénot Mar 21 '13 at 11:52
  • But maybe you have psychics skills and it's the good response =D – Gilles Quénot Mar 21 '13 at 11:54
  • Hi @sputnick, Read again my answers sputnick : "The simplest way would be to do ..." =) Benubird answer already shows the `mv` command needed to finish the OPs script. I simply show that this can be achieved without the need of variables. Might be useful to take a step back and not over complicate a simple task. – Chris Seymour Mar 21 '13 at 11:59
-2

Using the mv command. "mv" is short for "move".

mv $filetosend $filename
Benubird
  • 18,551
  • 27
  • 90
  • 141
  • 1
    You should note that the new file `$filename` will end up in the directory that the script is run from and not `/home/cft/` *(unless of course that is where the script is run from)*. You might want to use the aboslute path instead `mv "$filetosend" "/home/cft/$filename"`. – Chris Seymour Mar 21 '13 at 12:05