-3

I am trying to remove the text between /* and */ that is at the beginning of the file. There can be white spaces or new lines (\n) before or in-between /* and */.

I tried following but doesn't work when space or new lines are there.

sed '/^\/\*/,/\*\//d' file

Sample file:

   /*******
delete
bla

***
  */
/* do not */
print "hi"
/*******
dont delete
****/

Expected output:

/* do not */
print "hi"
/*******
dont delete
****/
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Sweety
  • 301
  • 1
  • 9
  • Does this answer your question? [Regex to remove multi line comments](https://stackoverflow.com/questions/2458785/regex-to-remove-multi-line-comments) – Bren Jul 10 '20 at 23:43
  • It doesn't help. Tried on my file, but it doesn't delete anything. – Sweety Jul 10 '20 at 23:46
  • Please, avoid changing rules when you have 2 answers https://stackoverflow.com/posts/62843678/revisions – Gilles Quénot Jul 11 '20 at 00:11
  • if the first line is `X /* blah...`, is `X` supposed to be removed from output? What about the spaces immediately following `X` ? – M. Nejat Aydin Jul 11 '20 at 01:52
  • What should the output be if the first line of the input file is `print "/* uh-oh */"`? You need a parser for whatever language your input file is written in to do this job robustly. – Ed Morton Jul 11 '20 at 03:15

3 Answers3

1

If ed is available.

printf '%s\n' '/^[[:space:]]*\//;/^[[:space:]]*\*\//d' ,p Q | ed -s file.txt
  • Change Q to w to edit the file.
Jetchisel
  • 7,493
  • 2
  • 19
  • 18
1

Using any awk in any shell on every UNIX box, this will produce the output you want from the input you provided:

$ awk 'f; /\*\//{f=1}' file
/* do not */
print "hi"
/*******
dont delete
****/

but consider also this more general approach:

$ cat tst.awk
{ rec = (NR>1 ? rec ORS : "") $0 }
END {
    $0 = rec

    gsub(/@/,"@A"); gsub(/{/,"@B"); gsub(/}/,"@C")
    gsub(/\/\*/,"{"); gsub(/\*\//,"}")

    sub(/^[[:space:]]*{[^}]*}[[:blank:]]*\n/,"")

    gsub(/}/,"*/"); gsub(/{/,"/*")
    gsub(/@C/,"}"); gsub(/@B/,"{"); gsub(/@A/,"@")

    print
}

.

$ awk -f tst.awk file
/* do not */
print "hi"
/*******
dont delete
****/

See https://stackoverflow.com/a/56658441/1745001 for an explanation of what those gsub()s are doing.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0
 awk 'BEGIN{f=-1} /^ *\/\*+/{f++}f' file

/* do not */
print "hi"
/*******
dont delete
****/
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223