Printing the price
We are almost done. We only need to print the price, as we have stored the price in the file, we need to store it in the variable to print it according to our needs. We will use a while loop until the file reaches the end of the file and extract the only line into a variable. Finally, we use the echo command to print the price.
while read price do val=$price done <$output echo "The price of $coin is = $val"
For a layer of readable code, we’ll create functions for each task, i.e. for striping or scraping the webpage and for printing the price.
function strip_html(){ grep -oP '(?<=<span class="no-wrap" data-price-btc).*?(?=</span>)' $output >temp.txt sed -i 's/[^>]*>//g' temp.txt >$output sed -ni '1p' temp.txt >$output cp temp.txt $output rm temp.txt }
function print(){ while read price do val=$price done <$output echo "The price of $coin is = $val" }
Below is the complete implementation.
Making several modifications, such as clearing the output of cURL to /dev/null, will flush the output and make it loop a bit cleaner. If it shows any error, please remove those commands. We also took the user input and stored the value in the coin variable.
#!/bin/bash function strip_html(){ grep -oP '(?<=<span class="no-wrap" data-price-btc).*?(?=</span>)' $output >temp.txt sed -i 's/[^>]*>//g' temp.txt >$output sed -ni '1p' temp.txt >$output cp temp.txt $output rm temp.txt } function print(){ while read price do val=$price done <$output echo "The price of $coin is = $val" } read -p "enter the coin code : " coin url='https://www.coingecko.com/en/coins/'$coin'' output=price.txt touch $output temp.txt curl -o $output $url strip_html print
Shell Script to Scrape prices of Cryptocurrency coins in Linux
Cryptocurrency is such a hype that everyone wants to be a part of it. Even nerds and programmers want to dive into this amazing field because it is quite versatile and interesting in every aspect. So how about scraping the price of cryptocurrency coins such as bitcoin, ethereum, dogecoin, and a ton of other coins using shell script and coingecko.com.
There are tons of websites that show the pieces of various Cryptocurrencies but many of them have bots and security systems to avoid recursively accessing a website. So the safest option here is to use coingecko which is a great and massive platform for analyzing cryptocurrency and other aspects as well.