SED: Matching two patterns on one line

Hi I want to delete a line using sed if it matches 2 regexes on one line. EG line starts with / * and ends with * / (comment). This script will do most of this. sed -e '/ ^ / * / d' -e '/ * / $ / d' filename This script will remove all lines starting with * and ending with * /. I want it to only delete a row if it meets two criteria, not one.

+2


a source to share


3 answers


Try

sed '/^\/\*.*\*\/$/ d' filename



The key here is that you can sort two regex patterns into one by simply concatenating them with .*

that matches "any number of characters". Of course, this provides ordering between the two. The first pattern ^\/\*

must happen before the second \*\/$

for the matching pattern.

Also, since it *

has a special meaning in a regular expression, be sure to avoid your asters, just as you need to avoid your slashes.

+2


a source


this also outputs multiline comments

eg,



# cat file
blah blah /* comment */
words1
words2
/* multiline
   comments
/*
end

$ awk -vRS='*/'  '{ gsub(/\/\*.*/,""); }1' file
blah blah

words1
words2

      

you can add another filter in sed 's|\/\/.*||'

to filter out comments //

as well

0


a source


For your specific problem, you can do something as recommended by @echo. However, if you require a more general solution, such as where the regex matches are not tied to one end of the line or the other, or may be in any order on the line, or may even overlap, you would be something like the following sed script:

/regexp1/! b notboth
/regexp2/! b notboth
:both
# sed commands if both patterns match
n
:notboth
# sed commands if at least one pattern doesn't match
n

      

This takes advantage of sed's branching capabilities. The command b

jumps to the named label if the pattern match succeeds, and the final !

in pattern inverts the meaning of the match. therefore, roughly speaking,

Put this in a file, say foo.sed

and run it as sed -f foo.sed

.

0


a source







All Articles