GNU sed
doesn’t know the \d
shorthand, you can use either [0-9]
or [:digit:]
instead, and you need to enable extended regular expression (ERE) syntax with the -r
option for +
to be recognized as a metacharacter:
sed -ir 's/^[0-9]+\s+[0-9]+\s+[0-9]+\s+[A-Za-z]+\s+[0-9]+\s+[0-9]+:[0-9]+:[0-9]+\s+[0-9]+.*/&\nno comments/' tmp.txt
&
on the right is replaced with the whole match, so you don’t need to create a group. $
at the end is not necessary if your expression ends with .*
. The g
lobally flag makes sed
replace all matches in the line, that’s not needed when you already match the whole line. The i
flage makes the regex case-insensitive, but you did that already by using [A-Za-z]
and not [a-z]
or [A-Z]
, so you can omit that too.
Groups are not only a way to cut out parts of the match in order to use it in the replacement, they also serve as a way to combine sequences. In your case they come in handy to merge e.g.
[0-9]+\s+[0-9]+\s+[0-9]+\s+
to
([0-9]+\s+){3}
which shortens your regex:
sed -ir 's/^([0-9]+\s+){3}[A-Za-z]+\s+[0-9]+\s+([0-9]+:){2}[0-9]+\s+[0-9]+.*/&\nno comments/' tmp.txt
Example run
$ <s sed -r 's/^([0-9]+\s+){3}[A-Za-z]+\s+[0-9]+\s+([0-9]+:){2}[0-9]+\s+[0-9]+.*/&\nno comments/'
INV_YTEC_TR::
3 3 1 May 7 05:31:11 2019
no comments
CA AOI1 0 0 -1 -3176120 1602000 12
A 0.4
Further reading