Issue
How sed
is working on line match and occurrence based match patterns like below, where deleting or replacing a particular line ..
Below are some test, i could not understand why it only works on first matched and not on second.
Initial 10 line of the log file:
$ head smbd.log.old
[2020/02/16 03:53:55.112796, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 52391 -- ignoring
[2020/02/16 04:08:55.126564, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 52891 -- ignoring
[2020/02/16 04:23:55.209096, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 53648 -- ignoring
[2020/02/16 04:38:55.301910, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 54165 -- ignoring
[2020/02/16 04:53:55.382553, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 54920 -- ignoring
Changing the first matched string to "Change_to_new":
$ sed '0,/2020/s//Change_to_new /' smbd.log.old | head
[Change_to_new /02/16 03:53:55.112796, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 52391 -- ignoring
[2020/02/16 04:08:55.126564, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 52891 -- ignoring
[2020/02/16 04:23:55.209096, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 53648 -- ignoring
[2020/02/16 04:38:55.301910, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 54165 -- ignoring
[2020/02/16 04:53:55.382553, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 54920 -- ignoring
deleting the First match string:
$ sed '0,/2020/{//d;}' smbd.log.old | head
Could not find child 52391 -- ignoring
[2020/02/16 04:08:55.126564, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 52891 -- ignoring
[2020/02/16 04:23:55.209096, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 53648 -- ignoring
[2020/02/16 04:38:55.301910, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 54165 -- ignoring
[2020/02/16 04:53:55.382553, 2] ../source3/smbd/server.c:576(remove_child_pid)
Could not find child 54920 -- ignoring
[2020/02/16 05:08:55.427916, 2] ../source3/smbd/server.c:576(remove_child_pid)
Why it did not work for Second match.
$ sed '1,/2020/{//d;}' smbd.log.old | head
sed: -e expression #1, char 0: no previous regular expression
Solution
Line address 0
is special. From GNU sed manual:
0,/regexp/
A line number of 0 can be used in an address specification like 0,/regexp/ so that sed will try to match regexp in the first input line too.....
Because sed
uses /regexp/
on the first line of input in 0,/regexp/
, the 0,/regexp/{//d}
works fine. But 1,/regexp/{//d}
does not work, because regexp
is unused on first line, so there were no previous matches.
Answered By - KamilCuk Answer Checked By - Mary Flores (WPSolving Volunteer)