kensaii
kensaii

Reputation: 314

shell/bash: use sed/awk to get string between special characters

suppose I have a string as

Al99.NegFRho.ZeroRhoR.ZeroPhiR.eam.alloy

I want to get 3 strings between 2 dots

NegFRho
ZeroRhoR
ZeroPhiR

how can I do it with sed or awk?

Upvotes: 2

Views: 70

Answers (2)

glenn jackman
glenn jackman

Reputation: 246807

With sed, you'd use

$ sed 's/^[^.]*\.\([^.]*\)\.\([^.]*\)\.\([^.]*\)\..*/\1\n\2\n\3/' <<<"$str"
NegFRho
ZeroRhoR
ZeroPhiR

Or, GNU grep:

$ grep -oP '\.\K[^.]+'  <<<"$str" | head -3
NegFRho
ZeroRhoR
ZeroPhiR

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You can use awk:

str='Al99.NegFRho.ZeroRhoR.ZeroPhiR.eam.alloy'
awk -F. -v OFS='\n' '{print $2, $3, $4}' <<< "$str"

NegFRho
ZeroRhoR
ZeroPhiR

Another smaller awk variant using RS:

awk -v RS=. 'NR>=2 && NR<=4' <<< "$str"

NegFRho
ZeroRhoR
ZeroPhiR

Upvotes: 4

Related Questions