5

I want a shell script to get MMDDYYYY from the file with a name as mentioned below file

linuxbox.23566.MMDDYYYYHHMMSS.zip
0

2 Answers 2

4

Using bash string functions:

for file in *.zip; do 
    file="${file%.*}"
    file="${file##*.}"
    echo "${file:0:8}"
done

Explaination:

  • file="${file%.*}": Gets rid of the extension and stores the new name in file variable
  • file="${file##*.}": Gets rid of the longest match from beginning and stores the name in file variable
  • echo "${file:0:8}": echoes the first 8 characters of whats left.

Demo:

$ ls
linuxbox.23566.MMDDYYYYHHMMSS.zip
$ for file in *; do file="${file%.*}"; file="${file##*.}"; echo "${file:0:8}"; done
MMDDYYYY
Sign up to request clarification or add additional context in comments.

Comments

1

With cut:

$ cut -d. -f3 <<< "linuxbox.23566.MMDDYYYYHHMMSS.zip" | cut -c-8
MMDDYYYY

Because the first part is returning:

$ cut -d. -f3 <<< "linuxbox.23566.MMDDYYYYHHMMSS.zip"
MMDDYYYYHHMMSS

And then it gets the first 8 chars.

2 Comments

the above is working in terminal. If i'm adding this in shell scripting this is not working. Can you provide shell script for the above command
What did you exactly try? Please update your question showing what you did.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.