Debian Codegraph @

strip-comments.sh

raw symbols SCIP
1 #!/bin/bash
2 # strip-comment.sh: Strips out the comments (/* COMMENT */) in a C program.
3
4 E_NOARGS=0
5 E_ARGERROR=66
6 E_WRONG_FILE_TYPE=67
7
8 if [ $# -eq "$E_NOARGS" ]
9 then
10 echo "Usage: `basename $0` C-program-file" >&2 # Error message to stderr.
11 exit $E_ARGERROR
12 fi
13
14 # Test for correct file type.
15 type=`file $1 | awk '{ print $2, $3, $4, $5 }'`
16 # "file $1" echoes file type . . .
17 # Then awk removes the first field, the filename . . .
18 # Then the result is fed into the variable "type."
19 correct_type="ASCII C program text"
20
21 if [ "$type" != "$correct_type" ]
22 then
23 echo
24 echo "This script works on C program files only."
25 echo
26 exit $E_WRONG_FILE_TYPE
27 fi
28
29
30 # Rather cryptic sed script:
31 #--------
32 sed '
33 /^\/\*/d
34 /.*\*\//d
35 ' $1
36 #--------
37 # Easy to understand if you take several hours to learn sed fundamentals.
38
39
40 # Need to add one more line to the sed script to deal with
41 #+ case where line of code has a comment following it on same line.
42 # This is left as a non-trivial exercise.
43
44 # Also, the above code deletes non-comment lines with a "*/" . . .
45 #+ not a desirable result.
46
47 exit 0
48
49
50 # ----------------------------------------------------------------
51 # Code below this line will not execute because of 'exit 0' above.
52
53 # Stephane Chazelas suggests the following alternative:
54
55 usage() {
56 echo "Usage: `basename $0` C-program-file" >&2
57 exit 1
58 }
59
60 WEIRD=`echo -n -e '\377'` # or WEIRD=$'\377'
61 [[ $# -eq 1 ]] || usage
62 case `file "$1"` in
63 *"C program text"*) sed -e "s%/\*%${WEIRD}%g;s%\*/%${WEIRD}%g" "$1" \
64 | tr '\377\n' '\n\377' \
65 | sed -ne 'p;n' \
66 | tr -d '\n' | tr '\377' '\n';;
67 *) usage;;
68 esac
69
70 # This is still fooled by things like:
71 # printf("/*");
72 # or
73 # /* /* buggy embedded comment */
74 #
75 # To handle all special cases (comments in strings, comments in string
76 #+ where there is a \", \\" ...),
77 #+ the only way is to write a C parser (using lex or yacc perhaps?).
78
79 exit 0