Delimiters in Bash

I find bash as one of the most fluid languages. Problem is when ever I come accross people that say they know bash but do not use it because they prefere perl or php. They say they use perl or php because of easy database access and how you can split strings. Today I will explain how to split a string in bash, from a stream even, so you don’t have to load whole files. I will use /etc/passwd as an example so you can follow along.

cat /etc/passwd|while read line; do

IFS=”:”

read username pass auid agid agroup ahome ashell<<EOF

$line

EOF

echo $username

echo $pass

echo $auid

echo $agid

echo $agroup

echo $ahome

echo $ashell

echo “--------

done

Simplified version

IFS=”:”

read first_name last_name< <(echo “Jeff:Price”)

you could use this method on a never ending stream of data

Thats all for now.

Sponsored Link

4 thoughts on “Delimiters in Bash

  1. Hmm, not working for me. Outputs just a bunch of blank lines separated by the “——–” lines.

    I added #!/bin/bash at the top just to be sure and if I echo $line, it prints the lines from /etc/hosts without the colons, so it does appear to be doing something.

  2. The example was a dirty one, It may fail if the lines have comments such as #

    try this in a terminal

    IFS=”:”
    read a b c d<<EOF
    Hello:World:Apples:Oranges
    EOF
    echo $a
    unset IFS

  3. I played around with your script for a while and got it to work after making a few modifications.

    #!/bin/bash

    IFS=”:”

    while read username pass auid agid agroup ahome ashell

    do

    echo $username

    echo $pass

    echo $auid

    echo $agid

    echo $agroup

    echo $ahome

    echo $ashell

    echo “——–”

    sleep 1

    done < /etc/passwd

    exit 0

Leave a comment

Your email address will not be published. Required fields are marked *