awk substr example

In this post, we will see how to use awk substr to select substring.

awk command has a lot of useful functions. One of them is awk substr function.
awk substr function is useful to select substring from a string.

Syntax

awk(string,x,y)
Where String is input string.
x is starting position in string(index starts from 1)
y is number of characters starting from x (optional)

Let’s create a test file.

$ cat > test.txt

This is sample file

Let’s see some awk substr examples on above created file.

$awk ‘{print substr($1,1,1)}’ test.txt

T

awk ‘{print substr($3,3)}’ test.txt

mple

awk ‘{print substr($4,1,2)}’ test.txt

fi

awk ‘{print substr($0,9,6)}’ test.txt

sample

Let’s create another sample file

You can search text and apply substr on the result as well.
For example:

$ cat > test2.txt

Welcome to java2blog
This is sample file,thanks

Let’s search for “sample file” and print “thanks” from the result.

$ awk ‘/sample file/{print substr($4,6)}’ test2.txt

thanks

We have searched using ‘/text to be searched’/ and then applied substr function on the result.
That’s all about awk substr function.

Was this post helpful?

Leave a Reply

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