Bash Script – Delete Comments from a C program

I wrote a bash script to delete comments from a C program. C language will required /* and */ between the contents of the comment. Example as below:

MQLONG  Reason;      /* Qualifying reason      */
MQOD    ObjDesc = {MQOD_DEFAULT}; /* Object descriptor      */
MQLONG  OpenOptions; /* Options control MQOPEN *//*----------------------------------------- */
   /* Initialize the Object Descriptor (MQOD)  */
   /* control block.  (The remaining fields    */
   /* are already initialized.)                */
   strncpy( ObjDesc.ObjectName,
            MQ_Q_NAME_LENGTH );

This bash script will help to clear out whatever character contains between these 2 comment characters. I am using sed, which is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline) and also with some help from Regex. Script as below:

# Bash scripts to delete comments from a C program
Usage="Usage: {script name} {target file}"
if [ $# -eq 0 ]; then                   # if no argument specified
        echo $Usage                     # print Usage string value
        exit 1
until [ $# -eq 0 ]
        case $1 in
                -h) echo $Usage         # print Usage string value if argument is -h
                        exit 0;;
                *) FILE=$1              # declare the next argument as `FILE`
if [ ! -f $FILE ]; then                         # if the file is not exist
        echo "'$FILE' is not a exist"           # print the file name is not a exist
        exit 1                                  # terminate the program
        sed -i '/\*/s/\/\*.*\*\/$//' $FILE              # remove the comment using sed
        echo "Comments for $FILE has been removed"      # print the status

If the script name saved as comment_remover under root directory and the target file is /home/user1/program.c , you can execute the script as follow (make sure the script is executable):

$ /root/comment_remover /home/user1/program.c
Comments for /home/user1/program.c has been removed

It will turn the example I use above to:

MQLONG  Reason;
MQLONG  OpenOptions;
   strncpy( ObjDesc.ObjectName,
            MQ_Q_NAME_LENGTH );

I hope this will help some other people out there. Happy scripting!