-1

I'm trying to swap the date in a log file's name using a bash script. I cannot seem to get the date's to play nice however.

When I try to swap the dates using sed, the original date is still in the filename (I'm echoing instead of using mv for now):

#!/bin/bash
DATE=`date +%Y-%m-%d`
YESTERDATE= date -d 'yesterday 13:00' '+%Y-%m-%d'
echo "$DATE"
echo "$YESTERDATE"
for LOGFILE in *.$DATE;
do
    newfile="$(echo ${LOGFILE} |sed -e 's/$DATE/$YESTERDATE/')" ;
    echo "$newfile"
    #mv -- "$LOGFILE" "$newfile";
done

The log files I want changed are only the ones with todays date in them. The format is log_file.log.2018-07-17. I want it to be changed to log_file.log.2018-07-16.

Is the issue with how I am using variable names in the sed command?

GreenGodot
  • 4,260
  • 8
  • 29
  • 53
  • quick suggestion, try: `sed -e "s/$DATE/$YESTERDATE/"` – Sundeep Jul 17 '18 at 14:28
  • I think Sundeep is correct, the single quotes are preventing the variable expansion for DATE and YESTERDATE. Change that line as Sundeep has suggested: newfile="$(echo ${LOGFILE} |sed -e "s/$DATE/$YESTERDATE/")" with $() the nested quotes will be fine. – Kyle Burton Jul 17 '18 at 14:31
  • 1
    Replace `YESTERDATE= date -d 'yesterday 13:00' '+%Y-%m-%d'` with `YESTERDATE="$(date -d 'yesterday 13:00' '+%Y-%m-%d')"` – Inian Jul 17 '18 at 14:33
  • See http://rextester.com/LHNH4768. Inian is right, the `$YESTERDATE` variable is empty when inside `for` loop if you do not place its definition inside `"$()"`. – Wiktor Stribiżew Jul 17 '18 at 14:35
  • The tool `sed` is dated. A lot of features are missing in this tool. Why not use a modern scripting language? – guettli Jul 17 '18 at 14:38

3 Answers3

1

You have a problem with quoting. This line

newfile="$(echo ${LOGFILE} |sed -e 's/$DATE/$YESTERDATE/')"

uses single quotes for the sed - and single quotes prevent the variables being substituted. You'll see the problem if you try something simple like

echo "$(echo '$foo')"

Instead, try

newfile=$(echo ${LOGFILE} |sed -e "s/$DATE/$YESTERDATE/")
Jon
  • 3,283
  • 2
  • 13
  • 22
0

One thing it's "", second it's bad YESTERDATE try to echo it. For me working something like this:

#!/bin/bash
DATE=`date +%Y-%m-%d`
#change No.1
YESTERDATE=$(date -d 'yesterday 13:00' '+%Y-%m-%d')
echo "$DATE"
echo "$YESTERDATE"
for LOGFILE in *.$DATE;
do
    #change No.2
    newfile="$(echo ${LOGFILE} |sed -e "s/$DATE/$YESTERDATE/")" ;
    echo "$newfile"
    #mv -- "$LOGFILE" "$newfile";
done
3sky
  • 750
  • 1
  • 5
  • 15
0

Hi modify below line in your script like :-

 newfile=$(echo ${LOGFILE} | sed -e 's/'$DATE'/'$YESTERDATE'/')

in sed, string variable should be under single quote '

Abhijit Pritam Dutta
  • 5,010
  • 2
  • 6
  • 16