Score:0

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

cn flag

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?

pLumo avatar
in flag
I don't really get if you want the file name as a variable or change/rename the file? Anyways, what did you try? Also, please describe your actual use case and give us some real input.
24601 avatar
in flag
please read [ask] then [edit] your question accordingly
MAHELI PAUL avatar
cn flag
Hi...filename mahelipaul_YYYYMMDDHHMMSS, I need to remove timestamp part i.e HHMMSS ..how can i get using linux command?
Score:1
cn flag

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.

Score:1
vn flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.