Manipulating Field Delimiters with IFS in Shell Scripting
The IFS (Intenral Field Separator) variable in shel scripting controls how the shell interprets word boundaries. By default, it includes space, tab, and newline characters. Modifying IFS allows for custom string segmentation.
Setting IFS to IFS=$'\n':;" would make newline, colon, semicolon, and double quote characters delimiters. Conversely, IFS=' ' treats the literal characters '' and 'n' as a newline, while IFS=$'\n' correctly sets the newline character as the delimiter. Using IFS=' ':;" would define backslash, 'n', colon, semicolon, and double quote as separators.
Splitting Strings into Arrays
1. Using IFS for Splitting
str="192.168.31.65"
OLD_IFS="$IFS"
IFS="."
array=($str)
IFS="$OLD_IFS"
for index in "${!array[@]}"; do
echo "Index $index => ${array[index]}"
done
This approach saves the original IFS, sets the period as the delimiter, splits the string into a array, and then restores IFS.
2. String Substitution for Array Construction
str="192.168.31.65"
array=(${str//./ })
for index in "${!array[@]}"; do
echo "Index $index => ${array[index]}"
done
This method uses shell parameter expansion (${str//./ }) to replace periods with spaces before creating the array.
Iterating Over Command Output Lines
When processing the output of commands, a for loop is often used. The default IFS handles space-separated output, like the result of ls:
for filename in $(ls);
do
# process filename
done
However, for multi-line command output, such as ls -lrt, the default IFS is insufficient. To iterate line by line, modify IFS:
oldifs="$IFS"
IFS=$'\n'
for file_detail in $(ls -lrt);
do
# process file_detail (a single line of ls -lrt output)
echo "Processing: $file_detail"
done
IFS="$oldifs"
This snippet preserves the original IFS, sets it to a newline character to ensure line-by-line processing, executes the loop, and then restores the original IFS.