Ondřej Plátek Archive
PhD student@UFAL, Prague. LLM & TTS evaluation. Engineer. Researcher. Father.

Renaming files: parameter expansion is good but not so good

Why do I need it?


From time to time, I need to have more files in one directory than is healthy (I can not see them on one screen). In order to group them by simple ls command I need to change a prefix. As an example, I want to have separately labs and lectures:)

$ ls
Lecture1_LabTeacher_topicA.pdf
Lecture1_LectureTeacher_topicE.pdf
Lecture2_LabTeacher_topicF.pdf
Lecture2_LectureTeacher_topicB.pdf
Lecture3_LectureTeacher_topicC.pdf
Lecture4_LectureTeacher_topicD.pdf

Let us say, that I want to solve it by putting Lab prefix instead of Lecture prefix.

$ for F in *Lab*; do echo "${F}" "Lab${F#Lecture}"; done

Results:

Lab1_LabTeacher_topicA.pdf
Lab2_LabTeacher_topicF.pdf
Lecture1_LectureTeacher_topicE.pdf
Lecture2_LectureTeacher_topicB.pdf
Lecture3_LectureTeacher_topicC.pdf
Lecture4_LectureTeacher_topicD.pdf

Similarly variable expansion is useful for batch converting of images:

for I in *.jpg; do convert "$I" "${I%jpg}png" ; done

Drawbacks: If you need batch substitution


Not everything you can split into prefix, middle part and suffix. So I started using sed instead of bash substitution. In example below you can use both, bash variable expansion and sed. I choose it like a good example. Typical situation when I need substitution in arguments of commands is during renaming another set of lectures. Usually, we have 12-14 slides per semester, which makes a mess on command line.

$ ls
Lecture11.pdf
Lecture12.pdf
Lecture1.pdf
Lecture2.pdf
Lecture3.pdf
...
Lecture9.pdf

Renaming using sed substitution:

for F in *e[0-9].pdf; do mv "$F" `echo "$F"|sed s:Lecture:Lecture0:`; done