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
123,281,029 USD
342,019,929 EUR

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
  • 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 '14 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 '14 at 18:29

Using perl:

perl -ple 's/\s+//g unless /\d/' file

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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