Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Manipulating Field Delimiters with IFS in Shell Scripting

Tech May 8 3

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.

Tags: shellbashIFS

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.