Kasper Seweryn
Kasper Seweryn

Reputation: 366

How to redirect only newest line of output to file dynamically?

I have the following output:

artist - song name
artist - song name
artist - song name

When one song ends, the program prints next artist and song name in a new line. I want to pipe the output somehow and save only the latest entry to the file in the way that when there's a new entry, it overwrites the file.

Is it possible with simple piping in bash? Or do I have to write some wrapper script for that?

Upvotes: 0

Views: 80

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52441

Let's mock a program that prints a new artist / song title every few seconds with a shell function:

printsong() {
    local i=0
    while :; do
        echo "artist - song $((++i))"
        sleep 3
    done
}

Now, we read from this function, and overwrite a file every time we get a new line:

printsong | while IFS= read -r song; do echo "$song" > output; done

output will now always contain the most recent line of output from printsong.

Upvotes: 1

Related Questions