7
$\begingroup$

I'd like to emulate

ls -tlra | grep <search term>

in Wolfram. I have tried

Module[{},
  SetDirectory[dir]
  RunProcess[{"ls", "-tlra", "|", "grep", <searchTerm>}, "StandardOutput"]
]

which doesn't seem to work. Is there a way to use the "pipe" operator when shelling out commands in Wolfram?

$\endgroup$
1
  • 1
    $\begingroup$ Try prepending "bash","-c" as I show in this answer. $\endgroup$
    – Tim Laska
    Commented Sep 10, 2019 at 16:35

2 Answers 2

12
$\begingroup$

For example:

RunProcess[{"bash", "-c", 
  "ls -ltr | grep wolf "}, "StandardOutput", 
 ProcessDirectory -> $InstallationDirectory]
(* "-rwxr-x---+ 1 Administrators None  551360 Apr  8 09:51 \
wolfram.exe
-rwxr-x---+ 1 Administrators None 2390464 Apr  8 09:52 \
wolframscript.exe *)
$\endgroup$
2
$\begingroup$

To elaborate on the accepted answer.

I often need to run some Unix pipes to prepare data that I will then input to Mathematica. I tend to keep the data and notebooks in the same directory, so more common for me would be to use

(* set directory to the notebook directory *)
SetDirectory[NotebookDirectory[]]

(* grab the stdout from the pipe *)
raw = RunProcess[{
    "/bin/bash", "--login", "-c",
    "cat papers.jsonl | jq 'select (.title | contains(\"Tiger\"))'"
  }, 
  "StandardOutput", 
  ProcessDirectory -> NotebookDirectory[]
 ]

The original Unix pipe cat papers.jsonl | jq 'select (.title | contains("Tiger"))' was copied and pasted from the terminal inside an already typed "" pair. By doing so Mathematica will prompt you if you want to escape any quotes or backslashes (which one does).

The --login make the bash instance behave like the one I use on the command line. In my case that is important because the program jq, used to manipulate JSON, is not in a standard location. The file papers.jsonl, a collection of JSON objects, one per line, is in the same directory as the Mathematica notebook, so the ProcessDirectory option changes the shell's directory before its execution.

The SetDirectory[NotebookDirectory[]] line is typically at the top of the notebook.

$\endgroup$

Your Answer

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

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