Tuesday, August 14, 2012
11:31 PM

Bash Script: Using IFS to split the strings into tokens

IFS (Internal Field Separator) is one of Bash's internal variables. It determines how Bash recognizes fields, or word boundaries, when it interprets character strings.

$IFS defaults to whitespace (space, tab, and newline), but can be changed, below example show you how to change the IFS value to split the strings into tokens based on any delimiter, in our case we are using ':' to split the string into tokens.

Source: cat ifs.sh
#!/bin/bash

var="google:yahoo:microsoft:apple:oracle:hp:dell:toshiba:sun:redhat"
echo "Original value of IFS is: $IFS"

# Saving the original value of IFS
OLD_IFS=$IFS
IFS=:
echo "New value of IFS is: $IFS"
echo "================="

for word in $var;do
        echo -e $word
done <<< $var

echo "================"

# Restore the value of IFS back to the script.
IFS=$OLD_IFS
echo "Back to original value of IFS: $IFS"

Continue Reading...

0 comments:

Post a Comment