How to Extract Part of a String Using Bash_cut_split?


When programming, extracting specific parts of a string from a larger text is common. One popular method for this is using bash/cut/split commands in Linux/Unix. These commands are versatile and powerful, allowing extraction based on delimiters like spaces, commas, and semicolons. This article explores extracting string parts using bash/cut/split commands, providing practical examples for effective usage and for demonstration Ubuntu 22.04 is used.

Using cut command

The cut command is a powerful tool for extracting sections from files or strings. It can easily extract fields based on a delimiter or a specific character. Here is the syntax for the cut command:

cut -d [delimiter] -f [field] [name-of-file]

The cut command utilizes the -d option to specify the delimiter in the input file and the -f option to indicate the field(s) to be extracted. The filename argument represents the input file to be processed. As an example, let’s assume we have a file named file.txt with the following content:

Apple, 14Pro
LG, Q7
One Plus, 8Pro

To extract the second field from each line, you can employ the following shell script:

#!/bin/bash
cat file.txt
echo "The Extracted Part Of File is:"
cut -d ',' -f 2 file.txt

The output of the provided code, which displays the file and the extracted part, is as follows:

Using split command

The split command is a useful tool for dividing a string into an array of substrings using a specified delimiter. It is a built-in command in Bash that facilitates extracting a portion of a string. Here is the syntax for the split command:

IFS=[delimiter] read -ra [Name-of-array] <<< "$[string-to-be-extracted]"

In the provided bash script, the IFS variable defines the delimiter used in the string. The read command is responsible for reading the input and splitting it into an array. The <<< operator is utilized to pass the string as input. For instance, let’s consider a string named “Apple,14Pro” if the objective is to extract the second field, the following bash script can be used:

#!/bin/bash
cat file.txt
echo "The Extracted Part of File is:"

IFS=',' read -ra fields <<< "Apple,14Pro"
echo ${fields[1]}

By employing multiple variables in the read command, the Bash split command can be utilized to extract multiple fields from a string.

Conclusion

Bash offers multiple methods for extracting portions of a string, such as the cut and split commands. The cut command enables extraction of fields using a delimiter or specific character, while the split command divides a string into an array of substrings based on a delimiter. Proficiency in extracting parts of a string is a valuable skill for Bash scripting.

Print Friendly, PDF & Email
Categories