AWK Showing Output Flashcards

1
Q

How do you display AWK output?

A

Using print
or
printf

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Whats the diff between print and printf?

A

both will print the output, but printf will also do some formatting.

For example, it can show a textual string and format it into a column of a specific size.
It can even strip decimals from floating numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you search for a pattern using AWK?

A

awk /[pattern]/
where [pattern] is what you’re searching for.

the more complicated way to write it out is:
awk ‘($1 ~ /^(pattern1|pattern2)/) {print $2}’ filename

Where $1 first field is checked against pattern1 or pattern2 and it will print out the next field ($2) from the selected filename
likely a csv would fit this usecase well

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How would you print the Enviornment variables from a user?
Specifically, show the username stored in USER using AWK

A

awk ‘BEGIN { print ENVIRON[“USER”] }’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How would you determine other environment variables?

A

See the export command for other environment variables that may be available

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What would this output?
~~~
awk -F: ‘BEGIN {
printf “%-20s %s\n”, “Username”, “Home directory”
printf “%-20s %s\n”, “——–”,”————–”}
{ printf “%-20s %s\n”, $1, $(NF-1) }
‘ /etc/passwd
~~~

A

output:
~~~
Username Home directory
——– ————–
root /root
daemon /usr/sbin
bin /bin
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly