extracting date field from the lines Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of extracting date field from the lines without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a file like this

Sampleoutput1[Fri Jun 10 06:11:59 2016]Local/ESSBASE0///139929633446208/Error(10
Sampleoutput1Local/ESSBASE0///139929633446208/[Fri Jun 11 06:11:59 2016]Error(10

I need to extract date field and add this date as column with delimited ($).Date can be present anywhere in the file.

[Fri Jun 10 06:11:59 2016]$Sampleoutput1[Fri Jun 10 06:11:59 2016]Local/ESSBASE0///139929633446208/Error(10
[Fri Jun 11 06:11:59 2016]$Sampleoutput1Local/ESSBASE0///139929633446208/[Fri Jun 11 06:11:59 2016]Error(10

Answer

Assuming the date is always enclosed in [] and that’s the first [ on the line we can use a number of methods. Two common ones I use:

Using two cut commands (the lazy option, but it’s very easy to understand what it does):

cut -d'[' -f2 $srcfile | cut -d ']' -f1

The standard sed option, using a simple regex:

sed 's/.*[([^]]*)].*/1/' $srcfile

If your output is more complicated with multiple [ characters in it then you’ll need to use the sed option with a more complicated string:

sed 's/.*[(... ... .. ..:..:.. ....)].*/1/' $srcfile

EDIT: The revised question wants this added to the front of the string, leaving the rest of the line untouched. So we use the sed variant with a minor change:

sed 's/(.*[(... ... .. ..:..:.. ....)].*)/[2]$1/' $srcfile

Result:

[Fri Jun 10 06:11:59 2016]$Sampleoutput1[Fri Jun 10 06:11:59 2016]Local/ESSBASE0///139929633446208/Error(10
[Fri Jun 11 06:11:59 2016]$Sampleoutput1Local/ESSBASE0///139929633446208/[Fri Jun 11 06:11:59 2016]Error(10
We are here to answer your question about extracting date field from the lines - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji