Search code examples
fileunixwhile-loopifs

Problems Writing Output to File


I am reading in a small csv file in the format size,name - one set per line. For my testing file I have two lines in the csv file.

If I use the code

while
        IFS=',' read -r size name
do
        printf "%s\n" "name"
done < temp1.txt

The name values for each of the lines is printed to the terminal.

If I use the code

while
        IFS=',' read -r size name
do
        printf "%s\n" "name" > temp2.txt
done < temp1.txt

Then only the last name is printed to the temp2.txt file.

What am I doing wrong?!


Solution

  • You are using >, so that the file gets truncated every time. Instead, use >> to append:

    So it should be like this:

            printf "%s\n" "name" >> temp2.txt
                                 ^^
    

    All together:

    while
            IFS=',' read -r size name
    do
            printf "%s\n" "name" >> temp2.txt
    done < temp1.txt
    

    Basic example:

    $ echo "hello" > a
    $ echo "bye" > a
    $ cat a
    bye                        # just last line gets written
    
    $ echo "hello" >> a
    $ echo "bye" >> a
    $ cat a
    hello
    bye                        # everything gets written