How do i use a different field separator in bash for loop?



  • The default field separator is a space. If you want to change this you need to change the built-in shell variable called IFS, the Internal Field Separator. It's like other build shell variables like HOME and USER

           IFS    The  Internal  Field  Separator  that is used for word splitting
                  after expansion and to split lines  into  words  with  the  read
                  builtin  command.   The  default  value  is  ``<space><tab><new‐
                  line>''.
           IGNOREEOF
    

    First, we will look at the issue. Create a file with one line in the file.

    $ echo "Apples, Figs, Plums, Oranges are very good for health" > fruit.txt
    

    Create a script called forloop.sh.

    #!/bin/bash 
    for fruit in $(cat fruit.txt)
    do
    echo "Result: $fruit" 
    done
    

    Run the script. It takes the space as the field separator so you get the output incorrectly.

    $ ./forloop.sh 
    Result: Apples,
    Result: Figs,
    Result: Plums,
    Result: Oranges
    Result: are
    Result: very
    Result: good
    Result: for
    Result: health
    

    If we add the IFS variable into the script and change it to newline and then run the script again.

    #!/bin/bash 
    IFS=$'\n'
    for fruit in $(cat fruit.txt)
    do
    echo "Result: $fruit" 
    done
    

    Run the script. We get the result we want.

    $ ./forloop.sh
    Result: Apples, Figs, Plums, Oranges are very good for health
    

Log in to reply
 

© Lightnetics 2024