Skip to content

Instantly share code, notes, and snippets.

@nick3499
Last active October 25, 2018 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nick3499/266ba0046e2abdec34f8cc5f4c04a2f1 to your computer and use it in GitHub Desktop.
Save nick3499/266ba0046e2abdec34f8cc5f4c04a2f1 to your computer and use it in GitHub Desktop.
Bash: Display Top Hacker News Links in Firefox: cURL, IFS, delimiter, while loop, case statement, HTML template
#!/bin/bash
# Push links of top Hacker News posts to HTML file, then view in Firefox
# Based on: https://www.linuxjournal.com/content/parsing-rss-news-feed-bash-script
# `$ bash top-hn.sh > top.html`
# get top Hacker News RSS XML blob
sudo curl https://news.ycombinator.com/rss -o top-hn.xml
# `xmlgetnext()` sets internal field separator as `>` and delimiter as `<`
# to separate XML tags into `TAG` and `VALUE` fields
xmlgetnext () {
local IFS='>' # internal field separator
read -d '<' TAG VALUE # delimiter
}
# XML code is piped to the while-looped `xmlgetnext()`
# a case statement (pattern-matching expression)
# matches fields for the HTML template
# http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_03.html
cat top-hn.xml | while xmlgetnext ; do
case $TAG in
'item')
title=''
link=''
pubDate=''
;;
'title')
title="$VALUE"
;;
'link')
link="$VALUE"
;;
'pubDate')
pubDate="$VALUE"
;;
'/item')
cat<<EOF
<span>&#8226;</span><a href="$link"> $title</a><span style="color: #CCCCCC;"> ${pubDate/%?????/}</span><br>
EOF
;;
esac
done
firefox top.html
@nick3499
Copy link
Author

In a Unix-like terminal emulator:

$ bash top-hn.sh > top.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment