Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

Greece,Macedonia,Montenegro,Kosovo
Central African Republic,Chad,Republic of the Congo
share|improve this question

3 Answers 3

up vote 3 down vote accepted

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
share|improve this answer

this worked for me with a similar data set

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.