user1848018 user1848018 - 4 years ago 120
Linux Question

Find consecutive space delimited single characters in each line in bash

Let say I have the following file

Y M C A
cambridge m a
d m v office
t mobile


and want to convert it to

YMCA
cambridge ma
dmv office
t mobile


that is to detect all consecutive single characters followed by single space of different lengths ( greater than two). For example, the item 'd m v office', we should detect 'd m v' and convert it to 'dmv' but would leave 't mobile store' intact (only one single character).

Is it possible to do this in bash or I have to use a program like python to do this?

Answer Source

Perl one-liner:

echo 'Y M C A' | perl -ple's/\b\w\K\s(?=\w\b)//g'
==> YMCA

echo 't mobile' | perl -ple's/\b\w\K\s(?=\w\b)//g'
==> t mobile

This replaces a space when surrounded by a single word character. You can replace \w by [a-zA-Z] if it's more convenient for you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download