This is my date format in my file: [1/24/21 9:19:20:183 MYT]
.
I want to print all entries marked with timestamps from this moment onward to the end of the file. How can I do this using sed
?
Do you want to only print the date or the entire line containing the date?
To print the entire line, I would use grep '\[1/24/21 9:19:20:183 MYT\]' file
, but if you insist on using sed
, it can be accomplished with sed -n '/\[1\/24\/21 9:19:20:183 MYT\]/p' file
.
EDIT: Ugly backslashes can be avoided with grep -F
, as suggested by user freddy in the first comment below.
The -n
option ensures that lines are only displayed if they are explicitly printed by the sed
program. The p
command explicitly prints the line.
To only print the date, grep
is also the better solution. You just add the -o
or --only-matching
option. It should also be possible with sed
, but requires more skill than I have.
EDIT: OP actually has a different requirement and modified the question. You can give a line range to sed
. "from the line that contains [1/24/21 9:19:20:183 MYT] to the end" is written as /\[1\/24\/21 9:19:20:183 MYT\]/,$
. The dollar sign indicates the last line. So:
sed -n '/\[1\/24\/21 9:19:20:183 MYT\]/,$p' file
/usr/bin/grep' on Solaris systems is the legacy Solaris
grep` that's pre-POSIX. Solaris has quite a significant forward-compatibility guarantee going back over two decades, so legacy utilities with unique behaviors are kept around - Solaris awk
is almost legendary (or is that infamous?) in that regard. /usr/xpg4/bin/grep
is the POSIX-compliant grep
. And Solaris 11 probably has ggrep
, which would be GNU grep
.
Commented
Jan 25, 2021 at 15:29
If it doesn't have to be sed
, the following awk
program would work:
awk -v start="[1/24/21 9:19:20:183 MYT]" 'index($0,start)==1{f=1} f' file
This will parse the file until it finds a line starting with the string as specified in the start
variable. Once found, it sets a flag f
to 1. Lines are only printed if this flag is set.
This assumes a strict time ordering of entries, i.e. you cannot have "earlier" timestamps occuring after the line with the start
timestamp. Although improbable, this is possible in case of buffered logging.
gawk
, nawk
and mawk
on a Linux system and it worked in all cases. Can you post which awk
version you have?