How to get a list of URLs from an defined bookmark’s folder in Safari

applescriptbookmarkscommand linesafariterminal

Have many bookmarks in the Safari's Favorites. Let say, have an folder called perl and it contains many links and also subforlders with links, like in the screenshot:

enter image description here

Need to extract all bookmarked links from the perl folder and it's subfolders using ONLY Terminal's command line. E.g. want run some command in the Terminal, like:

get_my_bookmarks perl

and the result will be a list of URLs.

It is possible to achieve this with applescrit, e.g. with

 osascript -e '... some applescript voodoo ...'

or by using some tool and extracting the wanted links info from the binary ~/Library/Safari/Bookmarks.plist, e.g. the following

/usr/libexec/PlistBuddy -x -c Print ~/Library/Safari/Bookmarks.plist

dumps the whole plist (xml) – but how to easily extract only URLs from one defined bookmark-folder? Any idea for some simple way?

Best Answer

After some googling and learning XPath expressions, the solution is really simple:

The following shell script - let say its name is dump_bookmarks.sh,

#!/bin/bash
for foldername
do
    /usr/libexec/PlistBuddy -x -c Print ~/Library/Safari/Bookmarks.plist | \
    xmlstarlet sel --net -t -v "//key[.='Title']/following-sibling::string[.='$foldername']/parent::node()//key[.='URLString']/following-sibling::string[1]"
    echo    #print an newline after the last entry
done

and using it as

./print_bookmarks.sh perl  #argument is the bookmark-folder name

will print a list of bookmarked URLs, like for the above screenshot will print:

https://metacpan.org/pod/Path::Tiny
http://perlmaven.com/perl-based-open-source-products
http://www.perl.com/pub/2012/04/perlunicook-standard-preamble.html
https://acidcycles.wordpress.com/2010/11/24/implementing-factories-in-perl/
http://gcstar.softonic.com/
http://steffen-wendzel.blogspot.de/p/blog-page_24.html
http://continuity.tlt42.org/

For the script you need install the xmlstarlet command, for example using Macports

sudo port install xmlstarlet