Search code examples
bashcsvoutputechowget

Bash script generates line break - Why?


I made a small bash script which gets the current air pressure from a website and writes it into a variable. After the air pressure I would like to add the current date and write everything into a text file. The target should be a kind of CSV file.

My problem. I always get a line break between the air pressure and the date. Attempts to remove the line break by sed or tr '\n' have failed.

2nd guess from me: wget is done "too late" and echo is already done.

So I tried it with && between all commands. Same result.

Operating system is Linux. Where is my thinking error?

I can't get any further right now. Thanks in advance.

Sven

PS.: These are my first attempts with sed. This can be written certainly nicer ;)

#!/bin/bash

luftdruck=$(wget 'https://www.fg-wetter.de/aktuelle-messwerte/' -O aktuell.html && cat aktuell.html | grep -A 0 hPa | sed -e 's/<[^>]*>//g' | sed -e '/^-/d' | sed -e '/title/d' | sed -e 's/ hPa//g')

datum=$(date) 

echo -e "${luftdruck} ${datum}"  >> ausgabe.txt

Solution

  • The html file you download is using Windows line endings (Carriage Return \r + Line Feed \n). I assume your bash script only removes \ns, but the editor you are using to view the file is showing the \r as a linebreak.

    Therefore, you could pipe everything through tr -d \\r\\n which would remove all line breaks.

    But there is a better alternative: Extract only the important part instead of whole lines.

    luftdruck=$(
        wget 'https://www.fg-wetter.de/aktuelle-messwerte/' -O - |
        grep -o '[^>]*hPa' | tr -dc 0-9.
    )
    echo "$luftdruck $(date)" >> ausgabe.txt