In some directory I have a bunch of recorded TV programs. Every episode is on a separate mp4 file, and the filenames look like
1920x1080_yrjr_2021-03-02.mp4
1920x1080_yrjr_2021-03-03.mp4
1920x1080_yrjr_2021-03-09.mp4
...
The files are already in order because they have the date of broadcast as part of their names. However the names don't contain episode numbers. I know the first file is episode 321, the second file is episode 322, etc., and I want to rename them to
1920x1080_yrjr321_2021-03-02.mp4
1920x1080_yrjr322_2021-03-03.mp4
1920x1080_yrjr323_2021-03-09.mp4
...
To do this, the first step is to get the two substrings `1920x1080_yrjr` and `2021-03-02.mp4` from a given filename like `1920x1080_yrjr_2021-03-02.mp4`. The "cut" command comes in handy here. Say $FILE stores the filename, then
echo $FILE | cut -d '_' -f 1,2
will output `1920x1080_yrjr`. The `-d` flag tells the command to cut the string into segments using '_' as a delimiter. The `-f 1,2` option tells it to combine the first and the second segments in the output. Similarly,
echo $FILE | cut -d '_' -f 3
will give `2021-03-02.mp4` as output.
Therefore, the final command for batch renaming is
i=320; for FILE in *; do i=$((i + 1)); mv $FILE $(echo $FILE | cut -d '_' -f 1,2)$i\_$(echo $FILE | cut -d '_' -f 3); done