skip to Main Content

I have this file containing these contents

NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

I need to awk only the ID="centos" part. I tried:

awk /ID=/{print} file.txt

But this gives the output both ID="centos" and VERSION_ID="7"

How to only awk the string given in the pattern?

4

Answers


  1. Could you please try following(grep could be also used since question is about awk so going with it).

    awk '/^ID="/' Input_file
    
    • Use an anchor ^ to check if line starts from ID=.
    • Then add ID=" to make sure it only Matches ID= string NOT anything else.
    • Why string VERSION_ID= will not be matched because it is NOT starting from ID it contains ID, which is why we used ^ in our condition check.
    • awk works on method of pattern/condition then action so no action is mentioned here, that’s why default action printing of current line will happen.
    Login or Signup to reply.
  2. You can use awk if you like, but the normal tool for the job is simply grep with the REGEX anchored at the beginning of the line, e.g.

    $ grep '^ID=' /etc/os-release
    ID="centos"
    

    (that doesn’t mean there is anything wrong with using awk, but generally here you would think grep. I presume the file you are parsing is /etc/os-release)

    Login or Signup to reply.
  3. Your awk code with ^ goes perfectly:

    awk /^ID=/{print} file
    ID="centos"
    
    
    Login or Signup to reply.
  4. Use this for exact matching:

    $ awk -F= '$1=="ID"' file
    

    Output:

    ID="centos"
    

    If you need the field separator to be something else, use:

    $ awk 'split($0,a,/=/)&&a[1]=="ID"' file
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search