1

I have a text file as shown below:

where $ tells about EOL (end of line) location I have used to illustrate that.

 53t83t5  5 gejgi3 gg 4gij503 $

      /* rtdrfsetsrhs               $
ryhrdhrh               $
rhyrdhyyyyyyyyyyyrhyrshrh$
ryhrhrh */$
$
345dfeb terfgb$
/*srdtfgyhgfs*/           $
$
$

Now I have to replace every line of /* */ this block with EOL placed at start of the line as shown below, Notice the position of $ for Line 3 that means if there are some characters including whitespace we should not skip it instead we should place EOL at the position of /* forward slash.

 53t83t5  5 gejgi3 gg 4gij503 $

      $
$
$
$
$
345dfeb terfgb$
/*srdtfgyhgfs*/           $
$
$

I was able to detect the block using sed '/\/\*/,/\*\//d inputFile even I was able to delete the whole block also but I wonder can we do the above one using sed command in .sed script.

NOTE: /*...*/ this is used for illustration of a pattern block we can have different pattern enclosing blocks also, like <--...--> or !!...!! however I want to know a snippet for /*...*/, I can handle all others on my own.

2 Answers 2

1

From your expected output, it looks like you want to delete all but newline characters from the blocks that contain at least one newline character.

So you could use perl as:

perl -0777 -pe '
  s{/\* .*? \*/ | <-- .*? --> | !! .*? !!}{
    $& =~ /\n/ ? $& =~ s/[^\n]//gr : $&
  }gsex' < your-file
0
0

If it has to be sed, the following script does as per your example:

#!/usr/bin/sed -f

# if line contains "/*" we enter our "within-patterns" code-block
/\/\*/{
# however, lines must also _not_ contain "*/",
# because our specs wants us to leave those lines as is
    /\*\//!{
# first line within patterns, delete everything after the "/*"
        s%/\*.*%%
# this is a label to be used by "goto" (sed's 'b' command)
        :block
# display current line and read next one
        n
# if line just read does _not_ have "*/" end-of-block
        /\*\//!{
# delete whole line and
            s/.*//
# "goto" label "block" above
            bblock
        }
# we get here if current line _does_ contain "*/" end-of-block,
# in which case we delete everything up to the "*/"
        s%.*\*/%%
# then exit our "within-patterns" code-block.
    }
}

The approach is by having the script keep control over the looping while it is in "within block" mode, instead of letting sed do it automatically. This way we fine tune the manipulation of the lines within a block.

Note however that this is only for instructional purposes so to introduce a bit of more advanced sed constructs. This script would not be fully appropriate to parse comment lines out from actual C/XML/HTML/whatever source files, because those are typically much more complex than your sample scenario. See for instance this Q&A for more insight.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .