1

I am trying to insert a pattern named "no comments" after line "3 3 1 May 7 05:31:11 2019" in the following sample file

INV_YTEC_TR::
3 3 1 May  7 05:31:11 2019
CA AOI1 0 0 -1 -3176120 1602000 12
A 0.4

Tried following sed code but it didn't help.

sed -i 's/\(^\d+\s+\d+\s+\d+\s+[A-Za-z]+\s+\d+\s+\d+:\d+:\d+\s+\d+.*$\)/\1\nno comments/ig' tmp.txt 

Could someone please help me with the right sed command?

Regards, Shikha

0

1 Answer 1

1

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 globally 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

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .