0

I have a file with loads of from / to date strings taken from output of certificates files in the following format:

Jan 9 2015 Mar 2 2017

What would be the best way to split the string and store it in an array?

fromDate=Jan 9 2015
toDate=Mar 2 2017

Which I then want to apply the date command to

date $fromDate +%Y-%m-%d && date $toDate +%Y-%m-%d 

Would I use 3rd whitespace as a separator or is there a better way to do it?

1 Answer 1

3

There's no array involved.

You can read six things separated by whitespace, then group them together by doublequoting the variables:

#! /bin/bash
while read m1 d1 y1 m2 d2 y2 ; do
    date -d "$m1 $d1 $y1" +%Y-%m-%d
    date -d "$m2 $d2 $y2" +%Y-%m-%d 
done < <(echo Jan 9 2015 Mar 2 2017)

Replace the final <(echo ...) with the actual input.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! How could I get them to print on the same line?
to print them on the same line try: echo `date -d "$m1 $d1 $y1" +%Y-%m-%d` `date -d "$m2 $d2 $y2" +%Y-%m-%d`
Why not read m1 d1 y1 m2 d2 y2 <<< 'Jan 9 2015 Mar 2 2017' instead of while read ...; do ... done < <(echo ...)?
@BenjaminW.: Because the <(echo ...) is a placeholder of the input file which might contain more than one line.
Ah, I see "file" in the question now. Makes sense!

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.