-1

So I want a gvim or sed command which would insert a string (new_string) before the first match (//). For instance

Say the input is            --> hi hola //Comment
Then the output expected is --> hi hola new_string //Comment

So basically I want to add a string just before the first occurence of //. I tried the sed command

sed 's/\<\/\/\>/Really &/' file

However, this doesn't work for // substring.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Pradyuman Bissa
  • 171
  • 1
  • 9

1 Answers1

1

The \< and \> are word boundaries, but // are non-word chars. \< expects the next char to be a word char, and right before there must be start of a line or a non-word char. \> expects the end of string or non-word char immediately to the right and a word char immediately on the left. Thus, there is no match.

Also, it is a good idea to use regex delimiters other than / if you are using backslashes in the pattern or RHS.

Use

sed 's,//,new_string &,' file > newfile

It will replace // with new_string // once per line. If there is a need to replace the first occurrence in a whole file, see How to use sed to replace only the first occurrence in a file?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563