0

Input:

Job1 07/09/2018 22:40:57 01/20/2019 11:48:52
Job2 11/28/2018 19:23:49 01/20/2019 05:29:49

Expected output:

Job1 2018/09/07 22:40:57 2019/20/01 11:48:52
Job2 2018/28/11 19:23:49 2019/20/01 05:29:49

Change text from dd/mm/yyyy to yyyy/mm/dd, i.e replace the text

  • Pay for your needs – 炸鱼薯条德里克 Jan 20 at 16:39
  • I did not understand, don't downvote simply..! – Vishwanath Dalawai Jan 20 at 16:42
  • @VishwanathDalawai I am not the downvoter, but I expect it's because you haven't provided any details of what you have tried so far. Please edit the question to include that information as well. – Haxiel Jan 20 at 17:19
0

tl;dr

$ echo -e "Job1 07/09/2018 22:40:57 01/20/2019 11:48:52\nJob2 11/28/2018 19:23:49 01/20/2019 05:29:49" | sed 's/\([0-9]\+\)\/\([0-9]\+\)\/\([0-9]\{4\}\)/\3\/\2\/\1/g' -
Job1 2018/09/07 22:40:57 2019/20/01 11:48:52
Job2 2018/28/11 19:23:49 2019/20/01 05:29:49

sed command explained:

's/pattern/replacement/' this is the basic syntax

When we put a g at the end (like 's/pattern/replacement/g') it will do multiple replacements on one line.

[0-9] matches any one digit.

[0-9]* matches zero or more digits.

[0-9]\+ matches one or more digits (note: the backslash \ is an escape character; in this example we needed to escape +, because otherwise the bash would interpret it, not sed; also note that in other circumstances/uses it does not have to be escaped).

\/ is a slash /; again it must be escaped, but now because of sed, because we used / as separator around and between pattern and replacement; we could use any other character (like 's@pattern@replacement@' and then we would not need to replace the slashes /, but the at @ character (or any other character we used as separator).

[0-9]\{4\} matches 4 digits; again { and } must be escaped because of bash.

([0-9]) matches any one digit and ‘saves’ it for later (to memory); then, in replacement we can use this matched substring that is enclosed in brackets ( and ) (in this case a single digit). Again, we needed to escape them because of bash.

\1 is the first saved substring (see the previous paragraph); likewise \2 is the second one and \3 is the third one.

Therefore: \([0-9]\+\)\/\([0-9]\+\)\/\([0-9]\{4\}\) matches a date in dd/mm/yyyy or d/m/yyyy format.

\3\/\2\/\1 is a replacement, which consists of \3 (the third substring, the year), \/ is a slash, \2 (the second substring, the month), again \/ (a slash), and finally \1 (the first substring, the day of month).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.