phpsed

Remove Tabs Within Remark


i would like to remove the tabs within the comments, such as this sample;

<?php

                    //this is a comment with tab
$tes = 1;
$this->HTTP_URL = str_replace('///', '//', $this->http.$this->serverName.$this->port.$_SERVER['PHP_SELF']);
if ($tes == 1) {
    //this is a comment with tab
    echo $tes;
}

            //this is a comment with tab
$tes = 2;

I've tested it with;

sed -e 's|/*.*/||g' -e 's|//.||g' test.php > test2.php

But the result is;

this is a comment with tab
$tes = 1;
', $this->http.$this->serverName.$this->port.$_SERVER['PHP_SELF']);
if ($tes == 1) {
this is a comment with tab
    echo $tes;
}

this is a comment with tab
$tes = 2;

I want it to look like;

//this is a comment with tab
$tes = 1;
$this->HTTP_URL = str_replace('///', '//', $this->http.$this->serverName.$this->port.$_SERVER['PHP_SELF']);
if ($tes == 1) {
//this is a comment with tab
    echo $tes;
}

//this is a comment with tab
$tes = 2;

or even better with

/* this is a comment with tab */
$tes = 1;
$this->HTTP_URL = str_replace('///', '//', $this->http.$this->serverName.$this->port.$_SERVER['PHP_SELF']);
if ($tes == 1) {
/* this is a comment with tab */
    echo $tes;
}

/* this is a comment with tab */
$tes = 2;

I've tried various way, yet still have not come to the result i wanted. Thank you.

....

i've tried with

gsed -i 's|^\s*//|//|' test.php

and then

gsed -i ':a;$!{N;ba};s/^/\x00/;tb;:b;s/\x00$//;t;s/\x00\(\/\*[^*]*\*\+\([^/*][^*]*\*\+\)*\/\)/\1\x00/;tb;s/\x00\/\/\([^\n]*\)/\/*\1\*\/\x00/;tb;s/\x00\(.\)/\1\x00/;tb' test.php 

but the result is

<?php

/*this is a comment with tab*/
$tes = 1;
$this->HTTP_URL = str_replace('/*/', '//', $this->http.$this->serverName.$this->port.$_SERVER['PHP_SELF']);*/
if ($tes == 1) {
/*this is a comment with tab*/
    echo $tes;
}

/*this is a comment with tab*/
$tes = 2;

notice the error line 4

$this->HTTP_URL = str_replace('/*/', '//', $this->http.$this->serverName.$this->port.$_SERVER['PHP_SELF']);*/

it should not be replaced. need another syntax


Solution

  • This might work for you (GNU sed):

    sed -i 's|^\s*//|//|' file
    

    This removes zero or more spaces or tabs (white space) from the start of lines whose first two non-white space characters are //.

    If it is only tabs you want removed:

    sed -i s|^\t*//|//|' file
    

    N.B. This may substitute nothing for nothing i.e. a line beginning with // will still effect a substitution so the last solution should be:

    sed -i 's|^\t\+//|//|' file
    

    EDIT:

    sed -i 's|^\t\+//\(.*\)$|/*\1*/' file
    

    Or change // regardless:

    sed -i 's|^\t\+//|//|;s|//\(.*\)|/*\1*/|' file