I am trying to randomize the start index based on the total results available from the result set so that I can retrieve a random video result via the YouTube GData API. There are two ways I thought I could do this. The first, save the total number of results to a bash variable and just make 2 API requests, and the second to actually retrieve the "random" video by randomizing start-index based on the total number of videos in the result set using the logic/comparison functions (seemingly) available in the API query itself.
The other way I thought may be possible would be using XData to use math functions in the query itself (ie: https://developers.google.com/youtube/2.0/developers_guide_protocol_partial#Fields_Formatting_Rules) but the little bit I played with that I was unable to get the feel for the required syntax as I'm not familiar with XData or the GData API.
I am currently trying the first method. Supress grep output but capture it in a variable is a very similar question to this, though none of the answers actually worked for what I'm attempting to do, and since this is using pcregrep instead of grep, and for a much more involved question, I assumed it would be better for me to ask a new question.
I am trying to save the output of pcregrep to a bash variable so that I can use it in another query via the YouTube GData API.
Example:
wget -q "https://gdata.youtube.com/feeds/api/videos?author=vice&fields=openSearch:totalResults" -O - | totalResults=`pcregrep -o1 '>([0-9]+)<' 2>&1` | echo $totalResults
That returns an empty variable, as does removing the output redirect (2>&1) as well as trying to surround the pcregrep with $().
How can I have the results from...
wget -q "https://gdata.youtube.com/feeds/api/videos?author=vice&fields=openSearch:totalResults" -O - | pcregrep -o1 '>([0-9]+)<'
...saved into a variable?
Is this the way I should be doing what I want or would the comparison/logic functions available in the actual search terms allow me to do what I want with a single API query? I would prefer a single API query if possible.
You need to put the entire command pipeline inside the $()
:
var=$(wget "http://gd...sults" -O - | pcregrep -o1 ">([0-9]+)<")
Also, you don't want to redirect STDERR here (2>&1
). That would only mess up your result.
If you're unsure which stream your command writes to, you can identify it with strace
:
$ strace wget "http://gd...sults" -O - 2>&1 | grep ^write
...
write(1, "<?xml version='1.0' encoding='UT"..., 123<?xml ve...ec/open) = 123
write(1, "searchrss/1.0/'><openSearch:tota"..., 77searchrss...</feed>) = 77
The first argument to write()
is the number of the file descriptor (in this case 1, i.e. STDOUT).