Bash script automatitation name change using date

I'm new to the shell/bash area. I've created this little script to change a name using the date command. The idea is to get something like this

1.txt=>2020-02.txt 

And it works, but I get the old file name 2020-02-1.txt added to the output.
This is my code so far:

# FOR LOOP TO RENAME FILES
cd /home/atlas/Documents/bash/CARPETA-ORIGEN
#UBICAR LA CARPETA
FILES=$(ls *.txt)
NEW="$(date +"%Y-%m")"
for FILE in $FILES do echo "Renaming $FILE to new-$FILE" mv $FILE $NEW-$FILE
done
2

1 Answer

I tried to reproduce your error. The result was:

  • 1.txt is renamed to 2020-02-1.txt,
  • 2.txt is renamed to 2020-02-2.txt,
  • ...and so on.

If you want to remove the old filename/index from the result (which creates problems because of name clashes - there can only be one file as output), you can change your script to

# FOR LOOP TO RENAME FILES
cd /home/atlas/Documents/bash/CARPETA-ORIGEN
#UBICAR LA CARPETA
FILES=$(ls *.txt)
NEW="$(date +"%Y-%m")"
for FILE in $FILES do echo "Renaming $FILE to new-$FILE" mv $FILE $NEW.txt
done

But I wouldn't recommend this, because you can only rename one .txt file per folder.
However, the output of the above script is

2020-02.txt

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like