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.

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

  1. Anonymous says:

    What is the content of file temp?

  2. Sumir says:

    Thanks for the example bro.

  3. jayashree says:

    I have an array
    s = r70 s70 r65 r60 s65
    I only want the outpu to be 70 70 65 60 65
    how do I get?
    can anyone help?

    • awk works on text files, usually formatted in columns. For your question, I would rather use
      a short python code. The best would be to ask on dedicated web pages such as stackoverflow.

    • DMike92 says:

      awk ‘{print substr($0,2)}’

    • miguelmx says:

      Little late, but I guess this may be easier with sed:

      $ s="r70 s70 r65 r60 s65"
      $ echo $s
      r70 s70 r65 r60 s65

      $ echo $s | sed 's/[a-z]//g'
      70 70 65 60 65

      With this you will be replacing every char from “a” to “z” with null.


    • noob says:

      echo r70 s70 r65 r60 s65 | awk ‘{gsub(/[a-z]/, “”)}1’
      70 70 65 60 65
      echo $s | awk ‘{gsub(/[a-z]/, “”)}1’
      70 70 65 60 65

  4. Thank you mate. Helped me out right away.

  5. noob says:
    echo $s | awk '{gsub(/[a-z]/, "")}1'
    70 70 65 60 65

Leave a Reply

Your email address will not be published.