1

Here's how I'm grepping for lines:

grep "random text" /

I want to curl based on the text found. This is what I've tried:

grep "random text" / | curl http://example.com/test.php?text=[TEXT HERE]

What I don't understand how to do is use the results of grep while curling. How can I replace [TEXT HERE] which the results of my grep so it's getting the correct url?

Chase
  • 115
  • 2
  • 8
  • 2
    `grep: /: Is a directory` – Cyrus Dec 26 '17 at 19:37
  • The solutions presented so far make different assumptions about what you want because you haven't been clear. Do you want one `curl` command per line of grep result, or do you want to send the entire grep result to a single `curl` command? – Gene Dec 26 '17 at 19:47

3 Answers3

3

Passing all results from grep in one request:

 curl --data-urlencode "text=$(grep PATTERN file)" "http://example.com/test.php"

One request per grep result:

Use a while loop in combination with read:

grep PATTERN file | while read -r value ; do
    curl --data-urlencode "text=${value}" "http://example.com/test.php"
done
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    The text probably needs to be url-encoded. It's also not clear that he wants to do a separate request for each matching line, or send it all as one request. – Barmar Dec 26 '17 at 19:45
2
grep 'random text' file | xargs -I {} curl 'http://example.com/test.php?text={}'
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

Put the output of grep in a variable, and put that variable in place of [TEXT HERE]

output=$(grep "random text" filename)
curl "http://example.com/test.php?text=$output"

The quotes are important, since ? has special meaning to the shell and $output might contain whitespace or wildcard characters that would otherwise be processed.

If $output can contain special URL characters, you need to URL-encode it. See How to urlencode data for curl command? for various ways to do this.

Barmar
  • 741,623
  • 53
  • 500
  • 612