Trying to comment a source file

Viewed 95

I am trying to comment lines of source so that something like LANG = 'ENG'; becomes // LANG = 'ENG';

There are over a thousand lines in the source file and 'ENG' is not unique but the entire line IS. I gave up on wild carding the spaces and just tried the entire extant line 'as-is' but no joy. Something like (commented shell)--

enter code here

#!/bin/bash
#if [  -n "$5" ] ; then
#if [ "$5" == "ENG" ] ; then

sed -i "s/'         LANG                                   = '\''ENG'\''/\/\/'       LANG'                                  
=  '\''ENG'\''/" vc.pas > vc.out

#fi
#fi

So it reduces down to a single line. No joy whatever I try. TIA ! Howie

3 Answers

This works for me, passing any whitespace through to the output:

$ echo "LANG='ENG';" | sed "s#^\(\s*LANG\s*=\s*'ENG'\s*;\)#// \1#"
// LANG='ENG';
$ echo "   LANG  = 'ENG'  ;   " | sed "s#^\(\s*LANG\s*=\s*'ENG'\s*;\)#// \1#"
//    LANG  = 'ENG'  ;   

Technically it needs double backslashes inside the double-quoted string, but because none of the sequences form a valid escape sequence, bash doesn't mind.

With GNU sed, use

sed -i "s,.*LANG *= *'ENG';.*,//&," vc.pas

where

  • -i - enables inline file modification
  • s - substitution command
  • , - delimiter
  • .*LANG *= *'ENG';.* - text containing LANG = 'ENG'; with any amount of spaces around =
  • //& - replaces the matched line with // and the line itself

Use a regular expression for the line selection, followed by a substitution. Put the replacement commands in a file:

$ cat dt.sed                                                                                                      
/^LANG[[:space:]]*=[[:space:]]*'[^']*'/s;^;// ;
$ 

Then run sed(1) with that script:

$ echo "LANG='FOO'" | sed -f dt.sed
// LANG='FOO'

This works on a Fedora 34 system, but should work on any Linux.

Related