toraritte / program

1 stars 0 forks source link

How to use the PCRE library in script? #3

Open toraritte opened 5 years ago

toraritte commented 5 years ago

Simply call the compiled binaries with os:cmd/1 or there should be a more efficient way? I may be overthinking this.

Side note: The re library is based on PCRE 8.x

toraritte commented 5 years ago

os:cmd/1 may not be the right way, because pcre2grep expects a file name, and submit a string requires some tricks that may not be portable on other OSs. ("The functions in this module are operating system-specific. Careless use of these functions results in programs that will only run on a specific platform.")

For example, these won't work on Ubuntu because even though they work in Bash, which is my chosen shell, but the system default is Dash:

  1. heredoc:

    17> os:cmd("./pcre2grep 'foo' <<<'foobar'").  
    "/bin/sh: 1: Syntax error: redirection unexpected\n"
  2. process subsitition:

    1> os:cmd("./pcre2grep 'foo' <(echo 'foobar')").
    "/bin/sh: 1: Syntax error: \"(\" unexpected\n"

Simple piping works though, but then again, not portable:

4> os:cmd("echo 'foobar' | ./pcre2grep 'foo'").
"foobar\n"

(This is also shown in the pcre2grep manual at "Calling external programs or scripts".)

https://stackoverflow.com/questions/2462317/bash-syntax-error-redirection-unexpected https://unix.stackexchange.com/questions/340718/how-do-i-bring-heredoc-text-into-a-shell-script-variable https://superuser.com/questions/939746/pass-text-to-program-expecting-a-file https://stackoverflow.com/questions/7691141/what-is-the-fastest-and-easiest-way-to-call-a-c-function-from-erlang-via-ports

toraritte commented 5 years ago

Any found solutions to use the C lib boil down to these: http://erlang.org/doc/tutorial/users_guide.html

toraritte commented 5 years ago

Keep in mind that "Backslash is an escape character within string syntax, like in C. So if you want your literal string to contain a backslash (...) you need to write "\" as you discovered".

13> os:cmd("echo 'foo blah is a bar' | ./pcre2grep '^foo \b(.*)\b is a \b(.*)\b$'").
[]
14> os:cmd("echo 'foo blah is a bar' | ./pcre2grep '^foo \\b(.*)\\b is a \\b(.*)\\b$'").
"foo blah is a bar\n"