MechaStorm
MechaStorm

Reputation: 1482

merge 2 regular expressions - get the first characters of a hyphenated string

Does anyone know how I can best merge the two sed commands in this statement:

$ echo "Apple-Boy-Cat" | sed 's/\B.//g;' | sed 's/-//g'
ABC

The above works fine but I have a nagging feeling that I am forgetting something that could avoid me running two separate sed statements.

I had tried to do sed 's/\B.//g;y/-//' but I get an error of an unterminated y command.

Upvotes: 0

Views: 56

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

You could use the regex alternation operator \|.

$ echo "Apple-Boy-Cat" | sed 's/\B.\|-//g'
ABC

Note that \B matches between two word characters or two non-word characters. It does the opposite of \b (which matches between a word character and a non-word character).

Upvotes: 2

Jotne
Jotne

Reputation: 41456

This is not sed, but shows how to use awk to get same result:

echo "Apple-Boy-Cat" | awk -F- '{for (i=1;i<=NF;i++) printf substr($i,1,1);print ""}'
ABC

It splits the string by -, then print the first letter of every word.

Upvotes: 1

Related Questions