tags:

views:

53

answers:

3

Hi I want to delete a line using sed if it matches 2 regular expressions in the same line. EG the line starts with /* and end with */ (comment). The following script will do most of that. sed -e '/^\/*/ d' -e '/*\/$/ d' filename This script will remove all lines that start with * and end with */. I want it to remove the line only if is meets both criteria not one.

+1  A: 

Try

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

The key here is that you can sorta combine two regex patterns into one, simply by connecting them with .*, which matches "any number of any character". Of course, this enforces an ordering between the two. The first pattern ^\/\* must occur before the second one \*\/$ for this particular pattern to match.

Also, since * has special meaning in regex, be sure to escape your astrices, just as you have to escape your slashes.

echo
A: 

this strips out multiline comments as well

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 to sed 's|\/\/.*||' to filter out // comments as well

ghostdog74
A: 

For your specific problem, you can do something along the lines recommended by @echo. However, if you need a more general solution, for instance, one where the regexp matches aren't anchored at one end of the line or the other, or might be in either order on the line, or might even overlap, you'll 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 uses sed's branching abilities. The b command branches to the named label if the pattern match succeeds, and the trailing ! on the pattern inverts the sense of the match. so, roughly,

Put this in a file, say foo.sed, and run it as sed -f foo.sed.

Dale Hagglund