Site icon LinuxCommands.site

How to use awk to select substring in linux/unix

Awk substr has built-in functions that can help us select substrings anywhere in the input string.

substr syntax

substr(s, m, n)

Examples

In the following awk example, we will use the awk substr built-in function to intercept the input string substring.

Test string:
awk:substr:substring

Output “substr” substring:

➜  ~ echo "awk:substr:substring" | awk '{print substr($0,5,6)}'
substr

Parameter explanationsubstr($0,5,6)

ok.

In the above example, we showed how to use the awk substr built-in function to intercept substrings.

Of course, for the above regular string, we can use awk delimiter to separate the fields.

➜  ~ echo "awk:substr:substring" | awk -F":" '{print $2}'
substr
➜  ~ echo "awk:substr:substring" | awk 'BEGIN{FS=":"}{print $2}'
substr

Of course, this method can only handle regular strings. Irregular strings, we can only use the substr function.

Exit mobile version