0

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
New contributor
Alejandro Ruiz is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • So what do you want to happen, exactly? presumably you are using a loop because the number of files is greater than 1. How do you propose to make the new names distinct? – steeldriver Feb 14 at 23:53
  • Change the name of all the files with the date without the old name. – Alejandro Ruiz Feb 15 at 1:30
0

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

Alejandro Ruiz is a new contributor. Be nice, and check out our Code of Conduct.

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.