linux poison RSS
linux poison Email

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"

Output: ./ifs.sh
Original value of IFS is: 

New value of IFS is: :
=================
google
yahoo
microsoft
apple
oracle
hp
dell
toshiba
sun
redhat
================
Back to original value of IFS: 

NOTE: The default $IFS variable is set to space/tab/newline, which isn’t easy to set in the shell, so it’s best to save the original IFS to another variable ($OLD_IFS), so you can restore it back to it's original value once you are done with the spiting the string.




0 comments:

Post a Comment

Related Posts with Thumbnails