Sometimes, In a bash script, you want to separate the strings based on delimiter and output multiple strings to save them into variables or for processing.
This tutorial helps to split strings with delimiter with examples in bash shell programming.
This article covers
- Extract the file name for a given full path
- getting the full file name
- Extension name
split a string using the awk command in a bash shell script
awk
is a Linux command which works in all bash and shell distributions. and returns the exit code with the result.
Input to awk is given with the pipe(|) symbol.
the given input string contains a string delimited by colon(:
) and prints the strings by removing the colon symbol
str="abc:def:ghi"
echo "$str" | awk -F':' '{print $1,$2,$3}'
output:
abc def ghi
split using IFS variable
The input contains strings delimited by a hyphen.
Used shell variable IFS
(Internal Field Separator) assigned with a hyphen.
Iterated string using for loop and print the string by removing the hyphen
input="one-two-three"
IFS='-' array=($input)
for element in "${array[@]}";
do
echo $element;
done
Output
output:
one
two
three