Skip to main content
Source Link
Quasímodo
  • 19.4k
  • 4
  • 41
  • 78

GNU awk manual provides an example with getline that does just that, which I copy here verbatim.

# Remove text between /* and */, inclusive
{
    while ((start = index($0, "/*")) != 0) {
        out = substr($0, 1, start - 1)  # leading part of the string
        rest = substr($0, start + 2)    # ... */ ...    
        while ((end = index(rest, "*/")) == 0) {  # is */ in trailing part?
            # get more text
            if (getline <= 0) {
                print("unexpected EOF or error:", ERRNO) > "/dev/stderr"
                exit
            }
            # build up the line using string concatenation
            rest = rest $0
        }
        rest = substr(rest, end + 2)  # remove comment
        # build up the output line using string concatenation
        $0 = out rest
    }
    print $0
}

Bear in mind that it joins mon/*comment*/key into monkey. As Stéphane Chazelas mentions in this answer, this may lead to an effectively different code, so consider changing $0 = out rest to $0 = out " " rest.

Save that in a file, say commentRemove.awk, and execute it on a inputfile:

awk -f commentRemove.awk inputfile
Post Made Community Wiki by Quasímodo