Reputation: 15581
I have a file which contains two values for abc...
keyword. I want to grab the latest date for matching abc...
string. After getting the date I also need to format the date by replacing /
with -
---other data
2018/01/15 01:56:14.944+0000 INFO newagent.bridge BridgeTLSAssetector::setupACBContext() - abc...
2018/02/14 01:56:14.944+0000 INFO newagent.bridge BridgeTLSAssetector::setupACBContext() - abc...
---other data
In the above example, my output should be 2018-02-14
. Here, I am fetching the line which contains abc...
value and only getting the line with latest date value. Then, I need to strip out the remaining string and fetch only the date value.
I am using the following sed
but it is not working
grep -iF "abc..." file.txt | tail -n 1 | sed -e 's/^[^|]*|[^|]*| *\([^ ]*\) .*/\1/' -e 's%/%-%g'
Upvotes: 0
Views: 916
Reputation: 28
Easy and more simple try this.
cat filename.txt | grep 'abc' | awk -F' ' '{print $1}'
As pattern abc always fix as per the given logs. So this will be more easier way to get desire output.
Upvotes: 0
Reputation: 16834
This does what you want:
grep -iF "abc..." file.txt | tail -n 1 | awk '{print $1}' | sed 's#/#-#g'
Outputs this:
2018-02-14
Upvotes: 1
Reputation: 16948
With awk:
$ awk '/abc\.\.\./{d=$1} END{gsub("/", "-", d); print d}' file.txt
2018-2-14
Something with sed:
tac file.txt | grep -Fi 'abc...' | sed 's/ .*//;s~/~-~g;q'
Upvotes: 1
Reputation: 20002
When you use sed
for matching a part of the date, you can have it match year. month, date and abc...
in one command.
sed -rn 's#([0-9]{4})/([0-9]{2})/([0-9]{2}).*abc[.]{3}.*#\1-\2-\3#p' file.txt | tail -1
Upvotes: 0
Reputation: 15293
Since you asked for sed
-
$: sed -nE ' / abc[.]{3}/x; $ { x; s! .*!!; s!/([0-9])/!/0\1/!g; s!/([0-9])$!/0\1!g; s!/!-!g; p; }' in
2018-02-14
arguments
-n
says don't print by default-E
says use extended regexesthe script
/ abc[.]{3}/x;
say on each line with abc...
swap the line for the buffer$ { x; s! .*!!; s!/([0-9])/!/0\1/!g; s!/([0-9])$!/0\1!g; s!/!-!g; p; }
says on the LAST line($
) do the set of commands inside the {}
.x
swaps the buffer to get the last saved record back.s! .*!!;
deletes everything from the first space (after the date)s!/([0-9])/!/0\1/!g;
adds a zero to the month if neededs!/([0-9])$!/0\1!g;
adds a zero to the day if neededs!/!-!g;
converts the /
's to dashesp
prints the resulting record.Upvotes: 0