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)
  • s : input string
  • m : start position
  • n : length of substring


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

Test string:

Output “substr” substring:

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

Parameter explanationsubstr($0,5,6)

  • $0: input string
  • 5: means starting from the fifth digit, including the fifth digit
  • 6: Substring character length


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}'
➜  ~ echo "awk:substr:substring" | awk 'BEGIN{FS=":"}{print $2}'

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

Add a Comment

Your email address will not be published. Required fields are marked *