Awk separate string is the most commonly used function, awk supports single delimiter separation and multiple delimiter separation.
Awk can use the awk -F option and awk FS variable to achieve string separation.
Let’s see how to use awk -F option and awk FS variable to separate strings in linux / unix.
awk uses delimiters to separate strings
Use awk FS variables to separate strings
We use awk FS variables to separate strings based on specific characters (also called delimiters). In the following example, we divide the string into multiple fields based on the “:” symbol, with field numbers from 1 to N.
➜ ~ echo "a:b:c:d:e:f" | awk 'BEGIN{FS=":";}{print $2}'
b
➜ ~
Use awk -F option to separate strings
➜ ~ echo "a:b:c:d:e:f" | awk -F":" '{print $2}'
b
![](https://www.linuxcommands.site/wp-content/uploads/2020/05/image-45-1024x130.png)
The delimiter can be any character, it can be a space, tab, etc. As follows:
➜ ~ echo "a b c d" | awk -F" " '{print $2,$4}'
b d
The above example demonstrates how awk separates strings based on a single delimiter, but in actual production, we need to use awk to separate multiple delimiters.
awk uses multiple delimiters to separate strings
In the following example, we use the awk -F option and awk FS variable to split the string based on multiple delimiters.
➜ ~ echo "a#b|c#d#e:f" | awk 'BEGIN{FS="[:#|]";}{print $2, $5}'
b e
➜ ~ echo "a#b|c#d#e:f" | awk -F"[:#|]" '{print $2, $5}'
b e
In the next article, we will introduce the awk OFS variable, which is a pair with awk FS. awk FS separates strings based on delimiters, and awk OFS uses delimiters to combine fields.