Debian Admin

Debian/Ubuntu Linux System Administration Tutorials,Howtos,Tips

  • RSS Subscribe

    subscribe to the Debian Admin RSS feed
  • Sponsors



  • Categories

  • Sponsors

  • Support DebianAdmin

    Amount $:
    Website(Optional):


  • Meta

  • Archives



Delimiters in Bash

Posted by sighK on May 29th, 2009

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

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.

  • Share/Bookmark

4 Responses to “Delimiters in Bash”

  1. Scott M Says:

    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. Jeff Price Says:

    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. garywk Says:

    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

  4. xleo Says:

    Array version:

    IFS=”:”; while read line; do array=($line); echo ${array[0]}; done < /etc/passwd

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>