GREP works in Terminal but not in Script

After a lengthly search for a solution, I have come to the conclusion that I can’t find the answer myself.:frowning:

when I use the following CLI in the terminal everything works just like it should:

textutil -convert txt -stdout /Path/To/File | grep -A 12 “TextToFind”

This will return “TextToFind” + the next 12 lines, which is just what I need. However when I run this script (in Smile) the entire contents of the file is returned.

set theData to (do shell script "textutil -convert txt -stdout " & quoted form of "/Path/To/File")
set theLine to "TextToFind"
set theResult to (do shell script "echo " & quoted form of theData & " | grep -A 12 \"" & theLine & "\"")

The reason I didn’t pipe the results of the TEXTUTIL command directly into GREP is that “TextToFind” will change each time I loop through my code to find the various data that I need.

I have seen “awk” and “sed” used in a number of posts, both in this forum and in various locations that I have googled. Unfortunately I haven’t been able to figure out how make this work for my needs.

“TextToFind” will change fequently but I will always need “TextToFind” and the next 12 lines from the file. Each different “TextToFind” will only be in the file once.

Ideally what I’d like to be able to do is to CURL the data from a website and GREP the data I need into records (1 record for each “TextToFind”). I figured once I got GREP working the way I needed it, I could add the CURL portion next.

Any help is greatly appreciated,
Brad Bumgarner, CTA

Does this work?

set theResult to (do shell script "echo " & quoted form of theData & " | grep -A 12 " &  theLine)

‘theLine’ is already text - just pass it as it is.

Brad,

I think the problem of your script is a missing ‘without altering line endings’ options at the first ‘do shell script’:

set theData to (do shell script "textutil -convert txt -stdout " & quoted form of "/Path/To/File" without altering line endings)
set theLine to "TextToFind"
set theResult to (do shell script "echo " & quoted form of theData & " | grep -A 12 \"" & theLine & "\"")

D.

Adam – thanks for the “cleaner” version of the CLI.

Dominik – “without altering line endings” was the problem. Thanks!

Brad Bumgarner, CTA