Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

sql - sed - replace multiline string between patterns in different lines

I have few .sql files that contain comments marked as '/* */' Comment can start and end at the same line, but mostly there is a multiline comment.

[UPDATED] Example:

    /*=======WHATEVER=======*/
    SELECT * FROM TABLE 
    WHERE
        /* PERIOD_DTE IN
                (SELECT MAX(PERIOD_DTE) 
                 FROM TABLE WHERE PERIOD_DTE < '1900-01-01')
                 AND FIELD1 = 100
                 AND FIELD2 IS NULL
        */
    FIELD3 IS NULL

Is it possible to use sed function for replace that kind of comment as an empty string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will do it for your example (with GNU sed):

sed 's_*/_
*/_' your_file | sed '//*/,/*//d'

The ways it's working is as follows:

  • In the first command I'm using _ as a pattern delimiter to avoid needing to escape the characters.
  • The first command breaks any single line comment into a multiple line comment so that we can deal with one situation in the second command.
  • The second command deletes everything including and between lines matching the patterns /* and */

So with the example input:

SELECT * FROM TABLE 
WHERE
    /* PERIOD_DTE IN
            (SELECT MAX(PERIOD_DTE) 
             FROM TABLE WHERE PERIOD_DTE < '1900-01-01')
             AND FIELD1 = 100
             AND FIELD2 IS NULL
    */
    /* SINGLE LINE COMMENT */
FIELD3 IS NULL

So the two steps are:

sed 's_*/_
*/_' your_file

outputs:

SELECT * FROM TABLE
WHERE
    /* PERIOD_DTE IN
            (SELECT MAX(PERIOD_DTE)
             FROM TABLE WHERE PERIOD_DTE < '1900-01-01')
             AND FIELD1 = 100
             AND FIELD2 IS NULL

*/
    /* SINGLE LINE COMMENT
*/
FIELD3 IS NULL

and

sed '//*/,/*//d'

outputs:

SELECT * FROM TABLE
WHERE
FIELD3 IS NULL

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...