What is the best way to remove distances in the following lines and output cdv format. Can this be done reasonably easily on the command line? I'd like to avoid having to write a full-blow script.

Greece 282 km, Macedonia 151 km, Montenegro 172 km, Kosovo 112 km
Central African Republic 797 km, Chad 1,094 km, Republic of the Congo 523

The output would be:

Central African Republic,Chad,Republic of the Congo

3 Answers 3


No idea what kind if format is that cdv, but seems you only need to remove the digits followed by optional unit of measurement, then compact the spaces after the remaining commas:

sed 's/ *[0-9]\+\(,[0-9]\+\)\?\( *km *\)\?//g;s/, \+/,/g' file.txt

For better readability, the same with extended regular expression (suitable for GNU sed):

sed -r 's/ *[0-9]+(,[0-9]+)?( *km *)?//g;s/, +/,/g' file.txt

this worked for me with a similar data set

sed -e 's/[0-9]*.[0-9]*.km//g' -e 's/\,\ /\,/g' <file>
  • 1
    You omitted the final “523”. (Or maybe turtle omitted a final “km”?)
    – manatwork
    Oct 24, 2012 at 13:55
  • ahh good catch, i didnt even notice the lack of km on the last value
    – h3rrmiller
    Oct 24, 2012 at 13:56

a little bit late to the party...here's a way to do this with GNU awk + sed

awk -F'[[:space:]]*[[:digit:],]+[[:space:]]*?km[[:space:],]*' 'BEGIN{OFS=","}{$1=$1;print}' | sed 's/,$//g'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .