Hacker News new | ask | show | jobs
by jsrn 3486 days ago
Nice!

To run this with macOS, I had to use the GNU version of sed. I installed it with

    $ brew install gnu-sed
And it is then called with 'gsed' instead of 'sed'.

As an avid Perl programmer, I had json_pp in my $PATH - for everyone else - it is here: https://metacpan.org/pod/JSON::PP

You can install it with cpanm:

    $ cpanm JSON::PP
If you don't have cpanm, you can install it with

    $ curl -L https://cpanmin.us | perl - App::cpanminus
The modified command line from above then becomes:

    $ curl -sS 'https://www.google.com/complete/search?client=hp&hl=en&xhr=t&q=aurora' \
        | json_pp | gsed -nE '/<\/?b>/{s```g;s`"|,|^ *``g;p}'
Here is a little Bash function to encapsulate this:

    $ function c() { curl -sS "https://www.google.com/complete/search?client=hp&hl=en&xhr=t&q=$1" | json_pp | gsed -nE '/<\/?b>/{s```g;s`"|,|^ *``g;p}'; }
Which then allows you to use it like this:

    $ c hacker
    hacker news
    hacker typer
    hackerrank
    hackerman
    hackers movie
    hacker fare
    hackerone
    hackers cast
    hacker pschorr
For spaces in your query, use a '+':

    $ c New+York
    new york times
    new york and company
    new york giants
    new york post
    new york daily news
    new york weather
2 comments

Improved version using jq. This properly URL encodes the query parameter and uses a much simpler sed command. Additionally the API returns UTF-8 encoded data when the user agent is specified. Requires curl >= 7.18.0.

    function c() {
        url='https://www.google.com/complete/search?client=hp&hl=en&xhr=t'
        # NB: user-agent must be specified to get back UTF-8 data!
        curl -H 'user-agent: Mozilla/5.0' -sSG --data-urlencode "q=$*" "$url" |
            jq -r .[1][][0] |
            sed 's,</\?b>,,g'
    }
Example:

    $ c ':)' ':('
    ) ( meaning
    ) ( emoticon
    ) ( ͡° ͜ʖ ͡°)
    ) ( emoticon meaning
You can use BSD sed by just inserting a semicolon into the sed pattern:

  sed -nE '/<\/?b>/{s```g;s`"|,|^ *``g;p;}'
(Edited to remove previous advice about inserting a newline)