2

How can extract lines that match the regexp string ^li from the text (not a file) below using sed or something?

 linux
 loan
 litmus
 launch

I tried grep but I couldn't find a way to search within a quoted text, not a text file.

grep -n -i "^li" "linux
loan
litmus
launch" 

Returns No such file or directory. And I don't want to save this text as a file before searching, if possible.

0

3 Answers 3

3

You need to use a herestring (<<<) here to pass the string as input to grep, herestring returns a file descriptor, grep can then operate on that:

$ grep -ni "^li" <<<"linux
loan
litmus
launch"

Output:

1:linux
3:litmus

If your shell doesn't support herestrings, many shells don't, you can print your string and pipe it to grep:

$ echo "linux
loan
litmus
launch" | grep -n -i "^li"
1:linux
3:litmus

Or use heredoc (<<):

$ grep -ni "^li" <<EOF
> linux
> loan
> litmus
> launch
> EOF
1:linux
3:litmus
0
0

You can just do:

grep \^li

And then start typing your stuff. grep will read the terminal. sed will do the same. Use CTRL+D to stop them, and ... >saved_output_file output redirections to save the effects.

0

With sed you can use the sed -n '/^li/p'

Using @heemayl example

$ echo "linux
> loan
> litmus
> launch" | sed -n '/^li/p'
linux
litmus
1
  • nice but the question is more about the input file than the command to use.. Commented Jan 22, 2016 at 18:11

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.