Strip comments from a string

From Rosetta Code
Revision as of 09:27, 30 October 2010 by rosettacode>Markhobley (Imported from markhobley.yi.org)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Strip comments from a string
You are encouraged to solve this task according to the task description, using any language you may know.

The task is to remove text that follow any of a set of comment markers, (in these examples a either a hash or a semicolon) from a string or input line.

The following examples will be truncated to just "apples, pears":

apples, pears # and bananas apples, pears ; and bananas

UNIX Shell

Works with: Bourne Shell

Traditional Unix shell implementations do not directly support string manipulation. In order to remove the comments from the string, the cut utility is utilized. However, the cut command does not support multiple delimiters, so it is necessary to invoke the utility twice in order to strip both the semicolon and hash prefixed comments:

<lang sh>

  1. Stripping comments from a string

foostring=`echo "$foostring" | cut -f 1 -d '#' | cut -f 1 -d ';'`

  1. Stripping comments from an input file

cut -f 1 -d '#' foobar.txt | cut -f 1 -d ';'

</lang>