How do I remove HHMMSS from a filename in Linux/Unix? [duplicate]

I have a filename mahelipaul_YYYYMMDDHHMMSS, I need to remove HHMMSS part from the file and assign it to a new variable.

I need file as mahelipaul_YYYYMMDD. How can I do it?


The most straightforward

filename=mahelipaul_20201231235959
echo mv "$filename" "${filename%??????}"     # remove the last 6 characters

Remove the echo if it looks right.

There are more complicated things that can be done to validate the suffix is 14 digits and ensure those digits represent a valid timestamp.


With Bash, you can use "slicing" to cut a number of characters from a string. It sounds like you want to remove the last 6 characters, and it can be done like this: (this is just another way of doing the same as in Glenn's answer)

$ filename=mahelipaul_20201231235959
$ echo "${filename::-6}"     # remove the last 6 characters
mahelipaul_20201231

If you want the opposite (to keep only the last 6 characters, then it goes like this:

$ filename=mahelipaul_20201231235959
$ echo "${filename:(-6)}"    # keep only the last 6 characters
235959

Note that I'm "just" assigning a variable and printing the new. You need to use these modified variables to create new variables, files or whatever you actually want to do.

I find this Bash reference really useful.