This looks a bit clunky. Why not process the data as it comes in?
bookmarks_count=$chunk_size
total_bookmarks_count=0
{
while [ $bookmarks_count -eq $chunk_size ]; do
chunk=$(wget … -O - "$EXPORT_URL?start=$total_bookmarks_count")
bookmarks_count=$(printf %s "$chunk" | grep -c "$bookmark_prefix")
total_bookmarks_count=$((total_bookmarks_count + bookmarks_count))
printf %s "$chunk" |
sed -e 's#><#>\n<#g' -e "$EXPORT_COMPATIBILITY" -e "$EXPORT_COMPATIBILITY"
done
echo '<\/posts>'
} >"$EXPORT_PATH"
You can even avoid storing each chunk in memory, though it's a bit trickier. Here's a method that only works in ksh and zsh; in other shells, the right-hand side of the pipeline runs in a subshell so the value of total_bookmarks_count is not updated.
{
total_bookmarks_count=0
while
wget … -O - "$EXPORT_URL?start=$bookmarks_count" |
sed -e … |
tee /dev/fd/3 |
this_chunk_size=$(grep -c "$bookmark_prefix")
[[ $this_chunk_size = $chunk_size ]]
do
((total_bookmarks_count += chunk_size))
done
echo '<\/posts>' >&3
} 3>"$EXPORT_PATH"
Here's a way to make this method work in other shells, where the only information you can get out of a pipeline is its return status.
: >"$EXPORT_PATH"
total_bookmarks_count=0
while
wget … -O - "$EXPORT_URL?start=$bookmarks_count" |
sed -e … |
tee -a "$EXPORT_PATH" |
[ $(grep -c "$bookmark_prefix") = $chunk_size ]
do
total_bookmarks_count=$((total_bookmarks_count + chunk_size))
done
echo '<\/posts>' >> "$EXPORT_PATH"
<postsor<postsand<post– Jaypal Nov 25 '11 at 0:25