First, you need to get a list of the files. You can use globbing for that, like *Classes.csv
.
Then, you need to loop over this list. If you start out like this, it should print out all of the files:
for file in *Classes.csv; do
printf %s\\n "$file"
done
If that looks right, you now need to know the filename you want to rename to. Here I will use the %
operator in a parameter expansion to clip the .csv
off the end. This is documented in man bash
and the POSIX shell specifications as removing the smallest matching suffix from the string.
for file in *Classes.csv; do
file_noext=${file%.csv}
printf '%s -> %s\n' "$file" "$file_noext"
done
That's halfway there, now we need to add the date and re-add the .csv suffix. The date is similar to %F format (2019-01-29
) but contains no hyphens. I would recommend using the %F format instead if you are free to choose, as it is more obvious to the casual observer that it is a date. For your format, you will need %Y%m%d
(see man 1 date
). I use the $(...)
command substitution syntax here to capture the output of the date
command.
today=$(date +%Y%m%d)
for file in *Classes.csv; do
file_noext=${file%.csv}
printf '%s -> %s\n' "$file" "${file_noext}_${today}.csv"
done
If all the output looks correct, you will want to make the final change and use mv
instead of just printing the filenames:
today=$(date +%Y%m%d)
for file in *Classes.csv; do
file_noext=${file%.csv}
mv -- "$file" "${file_noext}_${today}.csv"
done
And that should be all that's necessary.
Your question explicitly asked for a for
loop, but normally I would just use the util-linux
rename
utility:
rename 'Classes' "Classes_$(date +%Y%m%d)" ./*Classes.csv
Note that this one-liner will not work on Ubuntu Linux as they provide an incompatible rename
utility. (On such systems you will need to invoke it as rename.ul
)