Sezen
Sezen

Reputation: 457

Linux sed - Delete words do not start with a specific character

How to remove words that do not start with a specific character by sed?

Sample:

echo "--foo imhere -abc anotherone" | sed ...

Result must be;

"--foo -abc"

Upvotes: 1

Views: 1336

Answers (3)

Kent
Kent

Reputation: 195079

gnu sed with -r:

kent$ echo "--foo imhere -abc anotherone" | sed -r 's/^|\s[^-]\S*//g' 
--foo -abc

However I prefer awk to solve it, more straightforward:

awk '{for(i=1;i<=NF;i++)$i=($i~/^-/?$i:"")}7' 

output:

--foo  -abc 

Upvotes: 1

Lajos Veres
Lajos Veres

Reputation: 13725

echo "--foo imhere -abc anotherone" |\
sed -e 's/^/ /g' -e 's/ [^-][^ ]*//g' -e 's/^ *//g'

The first and last -e commands are needed if only when the first word can be wrong either.

Upvotes: 2

Federico Piazza
Federico Piazza

Reputation: 30995

You can use ssed to enable PCRE regex and then you can use this one:

(?<!-)\b\w+

Working demo

enter image description here

echo "--foo imhere -abc anotherone" | ssed 's/(?<!-)\b\w+//'

Upvotes: 0

Related Questions