nmh
nmh

Reputation: 501

Filter string only from line that matches regex

I've got some preceding code that outputs this line. Now I would like to isolate just the information in the 'us-west1-c' part. However, this information can change, albeit in the same format. For example, it would read 'us-east1-b' or 'europe-west2-c'. As a result the regex could be said to be *-*-* . However, I can't seem to find a way of filtering only this value from the line using this regex.

test-group  us-west1-c  zone   default  Yes      1

I've tried:

grep -ow '*-*-*'

Which produces no output.

I've also tried:

sed 's/.*\(*-*-*\).*/\1/'

Which again fails.

How, can I output only the string that matches my requirements?

Upvotes: 1

Views: 1039

Answers (3)

Alanpatchi
Alanpatchi

Reputation: 1199

This should work, i tested it.

grep "[^ ]*-[^ ]*-[^ ]*"

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

Now I would like to isolate just the information in the 'us-west1-c' part. However, this information can change, albeit in the same format. For example, it would read 'us-east1-b' or 'europe-west2-c'.

Your string has 6 "columns" and you want to get the value in Column 2. Use awk:

... | awk '{print $2;}'

See the online demo.

If there is just one value following *-*-* format, use

grep -o '[^ -]*-[^ -]*-[^ -]*'
# or
grep -o '[^[:blank:]-]*-[^[:blank:]-]*-[^[:blank:]-]*'

where [^[:blank:]-]* matches 0 or more chars other than whitespace and -. See another online demo.

Upvotes: 1

match
match

Reputation: 11070

You probably want something like:

 \w+-\w+-\w

Upvotes: 0

Related Questions