Have a try
awk -F: '{print $1, $NF}' /etc/passwd
part of command | Meaning |
---|---|
-F: | Colon as a separator |
{…} | Awk program |
Prints the current record | |
$1 | First field |
$NF | Last field |
/etc/passwd | Input data file |
Awk syntax:
awk [options] '[/pattern/] {action}' [input-file]
/pattern/
Execute actions only for matched pattern
awk -F: '/root/ {print $1}' /etc/passwd
BEGIN
block is executed once at the start
awk -F: 'BEGIN { print "uid"} { print $1 }' /etc/passwd
END
block is executed once at the end
awk -F: '{print $1} END { print "-done-"}' /etc/passwd
Build-in variables
Variable | Meaning |
---|---|
$0 |
Whole line |
$1, $2...$NF |
First, second… last field |
NR |
Number of Records |
NF |
Number of Fields |
OFS |
Output Field Separator (default “ “) |
FS |
input Field Separator (default “ “) |
ORS |
Output Record Separator (default “\n”) |
RS |
input Record Separator (default “\n”) |
FILENAME |
Name of the file |
Expressions
Expression | Meaning |
---|---|
$1 == "root" |
First field equals root |
{print $(NF-1)} |
Second last field |
NR!=1{print $0} |
From 2th record |
NR > 3 |
From 4th record |
NR == 1 |
First record |
END{print NR} |
Total records |
BEGIN{print OFMT} |
Output format |
{print NR, $0} |
Line number |
{print NR " " $0} |
Line number (tab) |
{$1 = NR; print} |
Replace 1th field with line number |
$NF > 4 |
Last field > 4 |
NR % 2 == 0 |
Even records |
NR==10, NR==20 |
Records 10 to 20 |
BEGIN{print ARGC} |
Total arguments |
ORS=NR%5?",":"\n" |
Concatenate records |
Awk Operators
Operator | Meaning |
---|---|
{print $1} |
First field |
$2 == "foo" |
Equals |
$2 != "foo" |
Not equals |
"foo" in array |
In array |
Regular expression | |
/regex/ |
Line matches |
!/regex/ |
Line not matches |
$1 ~ /regex/ |
Field matches |
$1 !~ /regex/ |
Field not matches |
More conditions | |
($2 <= 4 | $3 < 20) |
Or |
($1 == 4 && $3 < 20) |
And |
Examples
oc get pods | awk '$3 !~ "(Running|Completed|Creating)" {print $1}'