2

I know how to use the utility sed in bash, and grep is also good. But for the output, they always output a line containing the pattern.

Is there a way in bash to cut out a particular string containing the pattern I want (using regexp)?

1
  • grep -o is what you are looking for. Commented Feb 9, 2016 at 9:02

3 Answers 3

2

That's why you have --help flag, grep --help:

-o, --only-matching show only the part of a line matching PATTERN

Now you can

$ echo 'hello world' | grep -o hello
hello

Using sed:

$ echo "hello world" | sed 's/.*\(hello\).*/\1/'
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any way to use sed to do that? I am just curious, not for a particular goal.
Is the \1 affecting the result? I don't see any about this in the sed manual page.
@Chromium \1 is the first group, which is the hello. It's a regex thing.
so what does the command sed 's/.*\(hello\).*/\1/' really means?
It doesn't mean to translate the regexp to group first, right?
1

With GNU grep you can use -o:

-o Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Example:

$ echo ab cd ef gh | grep a
ab cd ef gh
$ echo ab cd ef gh | grep -o a
a

Comments

0

Through sed,

$ echo 'hello world' | sed 's/\(hello\)\|./\1/g'
hello

$ echo 'hello world' | sed -r 's/(hello)|./\1/g'
hello

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.