0

I have search string in one variable ($AUD_DATE) and replace string in another variable ($YEST_DATE). I need to search file name in a folder using $AUD_DATE and then replace it with $YEST_DATE.

I tried using this link to do it but its not working with variables. Find and replace filename recursively in a directory

shrivn1 $ AUD_DATE=140101
shrivn1 $ YEST_DATE=140124
shrivn1 $ ls *$AUD_DATE*
NULRL.PREM.DATA.CLRSFIFG.140101.dat  NULRL.PREM.DATA.CLRTVEH.140101.dat
shrivn1 $ ls *$AUD_DATE*.dat | awk '{a=$1; gsub("$AUD_DATE","$YEST_DATE");printf "mv \"%s\" \"%s\"\n", a, $1}'
mv "NULRL.PREM.DATA.CLRSFIFG.140101.dat" "NULRL.PREM.DATA.CLRSFIFG.140101.dat"
mv "NULRL.PREM.DATA.CLRTVEH.140101.dat" "NULRL.PREM.DATA.CLRTVEH.140101.dat"

Actual output I need is

mv "NULRL.PREM.DATA.CLRSFIFG.140101.dat" "NULRL.PREM.DATA.CLRSFIFG.140124.dat" 
mv "NULRL.PREM.DATA.CLRTVEH.140101.dat" "NULRL.PREM.DATA.CLRTVEH.140124.dat"

Thanks in advance

Community
  • 1
  • 1

1 Answers1

0

Approach 1

I generally create mv commands using sed and then pipe the output to sh. This approach allows me to see the commands that will be executed beforehand.

For example:

$ AUD_DATE=140101
$ YEST_DATE=140124
$ ls -1tr | grep "${AUD_DATE}" | sed "s/\(.*\)/mv \1 \1_${YEST_DATE}"

Once you are happpy with the output of the previous command;repeat it and pipe it's output to sh, like so:

$ ls -1tr | grep "${AUD_DATE}" | sed "s/\(.*\)/mv \1 \1_${YEST_DATE}" | sh

Approach 2

You could use xargs command.

ls -1tr | grep ${AUD_DATE}" | xargs -I target_file mv target_file target_file${YEST_DATE}
Rishabh Sagar
  • 1,744
  • 2
  • 17
  • 27
  • Thx @rishabh . But the 1st Approach has some parsing error and 2nd Approach is not providing the desired o/p. Its just appending $YEST_DATE to file name. – Nakul Shrivastva Jan 27 '14 at 07:05