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
Could you please try following(
grep
could be also used since question is aboutawk
so going with it).^
to check if line starts fromID=
.ID="
to make sure it only MatchesID=
string NOT anything else.VERSION_ID=
will not be matched because it is NOT starting fromID
it contains ID, which is why we used^
in our condition check.awk
works on method ofpattern
/condition
thenaction
so no action is mentioned here, that’s why default action printing of current line will happen.You can use
awk
if you like, but the normal tool for the job is simplygrep
with the REGEX anchored at the beginning of the line, e.g.(that doesn’t mean there is anything wrong with using
awk
, but generally here you would thinkgrep
. I presume the file you are parsing is/etc/os-release
)Your
awk
code with^
goes perfectly:Use this for exact matching:
Output:
If you need the field separator to be something else, use: