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.

I've been stumped with this seemingly simple-to-fix problem.. well, for a while.

Here's example output from the file I need to edit:

$cat file
George Washington
Geneva Convention
123,281,029 USD
342,019,929 EUR

I need to remove the spaces between "George Washington" and "Geneva Convention", but not the spaces between "123,281,029 USD" or "342,019,929 EUR".

Essentially, my goal here is to only remove the space between words in a line ONLY if there are no numbers in that line.

I've tried to edit the file via grep -v [0-9] $file | sed 's/ //', but only way that will work is if I output to another file, but that would mean excluding all lines with numbers from the old file to the new file, which is not what I need..

I've tried some pretty ridiculous loops with grep and sed but nothing seems to work just right.

Again, here is the example output of the file:

$cat file
George Washington
Geneva Convention
123,281,029 USD
342,019,929 EUR

Here is my desired output:

$cat file
GeorgeWashington
GenevaConvention
123,281,029 USD
342,019,929 EUR
share|improve this question
add comment

3 Answers 3

up vote 15 down vote accepted

Using sed:

sed '/[0-9]/!s/ //g' filename

This would remove spaces on all lines that do not contain a digit.

Using awk:

awk '!/[0-9]/{gsub(" ", "", $0)};1' filename

For removing the space only between the first two words (here using GNU sed for -r, use -E instead on BSDs):

sed -r '/[0-9]/!s/([^ ]+) ([^ ]+)/\1\2/' filename
share|improve this answer
    
Perfect! This is exactly what I was looking for! Couldn't find the syntax anywhere for the "/[0-9]/!s/" part. Thank you very much. –  user62129 Mar 6 at 18:20
    
@user62129 - if this answer solves your issue please take a minute and check the check mark under the vote count to the left, this will signify to everyone that your issue's been resolved. –  slm Mar 6 at 18:29
add comment

Using perl:

perl -ple 's/\s+//g unless /\d/' file
share|improve this answer
add comment

For a more general approach, remove only those spaces that are between two letters. That way it can work even if lines have digits, it just ignores the spaces around the numbers:

perl -pe 's/([a-z])\s+([a-z])/$1$2/ig' file

That will, for example, turn George and Harry 12 EUR to GerogeandHArry 12 EUR and still work correctly for the cases in your example.

share|improve this answer
add comment

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.