AWK: the substr command to select a substring

Under Linux, the awk command has quite a few useful functions. One of them, which is called substr, can be used to select a substring from the input.
Here is its syntax:

substr(s, a, b) : it returns b number of chars from string s, starting at position a. The parameter b is optional, in which case it means up to the end of the string.

For instance, consider a file with the following content:

every good

Let us save this data into a file called data.txt
Then, here are a few case examples:

awk '{print substr($1,1,1)}' data.txt   #returns e
awk '{print substr($1,3)   }' data.txt   #returns ery
awk '{print substr($2,3)   }' data.txt   #returns od
awk '{print substr($0,7,2) }' data.txt  #returns go
Please follow and like us:
This entry was posted in Linux and tagged . Bookmark the permalink.

12 Responses to AWK: the substr command to select a substring

Leave a Reply

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