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.

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

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
  • nice but the question is more about the input file than the command to use.. – heemayl Jan 22 '16 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.