Strip comments from a string: Difference between revisions

From Rosetta Code
Content added Content deleted
(Imported from markhobley.yi.org)
 
Line 23: Line 23:


</lang>
</lang>

The [[bash]] shell does include string manipulation facilities, so a different technique may be used on that shell:

{{works with|bash}}

<lang bash>

#!/bin/bash
# Strip comments from a string

</lang>

[[Category:String manipulation]]

Revision as of 09:31, 30 October 2010

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>

The bash shell does include string manipulation facilities, so a different technique may be used on that shell:

Works with: bash

<lang bash>

  1. !/bin/bash
  2. Strip comments from a string

</lang>