Extracting a Pattern-Based Substring
There are various ways to obtain substring based on the patterns of the string:
- using cut command
- using awk command
Method 1: Using cut command
For demonstration, take input strings to be comma-separated values: “Romy, Pushkar, Kareena, Katrina”. (-d ,) option is to be used with cut command to tell the command that the input string is comma separated values. -f option tell the cut command to extract the string based on the field like (-f 3) is for third field in the string.
Syntax:
cut [option] field_position <<< "comma_seperated_string"
Code:
cut -d, -f 3 <<< “Romy,Pushkar,Kareena,Katrina”.
This will extract third field.
Output:
Method 2: using awk command
Syntax:
awk [option] field_separator ‘{print $field_position}’ <<< “input_string”
Code:
To extract third field from string
awk -F’,’ ‘{print $1}’ <<< “Romy,Pushkar,Kareena,Katrina”
Output:
Bash Scripting – Substring
sIn this article, we will discuss how to write a bash script to extract substring from a string.