Kako uporabljati ukaz awk v Linuxu

V Linuxu  awkje dinamo za upravljanje besedila ukazne vrstice in močan skriptni jezik. Tukaj je uvod v nekatere najbolj kul lastnosti.

Kako awk je dobil ime

awk Ukaz je bil imenovan s pomočjo začetnice treh ljudi, ki so napisali izvirno različico leta 1977: Alfred Aho, Peter Weinberger in Brian Kernighan. Ti trije moški so bili iz legendarnega panteona Unix AT&T Bell Laboratories. S prispevki mnogih drugih od takrat awk naprej se še naprej razvija.

To je popoln skriptni jezik in celoten priročnik za upravljanje besedila za ukazno vrstico. Če vam ta članek povzroča apetit, si lahko ogledate vse podrobnosti o  awk njegovi funkcionalnosti.

Pravila, vzorci in dejanja

awkdela na programih, ki vsebujejo pravila, sestavljena iz vzorcev in dejanj. Dejanje se izvede nad besedilom, ki se ujema z vzorcem. Vzorci so zaprti v zavite oklepaje ( {}). Vzorec in dejanje skupaj tvorita pravilo. Celoten awkprogram je zajet v enojne narekovaje ( ').

Oglejmo si najpreprostejšo vrsto awkprograma. Nima vzorca, zato se ujema z vsako vrstico besedila, ki je vanj vstavljeno. To pomeni, da se dejanje izvede v vsaki vrstici. Uporabili ga bomo na izhodu iz whoukaza.

Tu je standardni izhod iz who:

WHO

Morda ne potrebujemo vseh teh informacij, ampak želimo samo videti imena na računih. Izhod lahko usmerimo whov awk, nato pa naročimo, awkda natisnemo samo prvo polje.

awkPolje privzeto šteje za niz znakov, obdanih s presledki, začetek vrstice ali konec vrstice. Polja so označena z znakom za dolar ( $) in številko. Torej  $1predstavlja prvo polje, ki ga bomo z print dejanjem uporabili za tiskanje prvega polja.

Vtipkamo naslednje:

kdo | awk '{print $ 1}'

awk natisne prvo polje in zavrže preostanek vrstice.

Natisnemo lahko poljubno število polj. Če dodamo vejico kot ločilo,  awkmed vsako polje natisne presledek.

Vtipkamo naslednje, da natisnemo tudi čas, ko se je oseba prijavila (polje štiri):

kdo | awk '{natisni $ 1, $ 4}'

Obstaja nekaj posebnih identifikatorjev polj. Ti predstavljajo celotno vrstico besedila in zadnje polje v vrstici besedila:

  • $ 0 : predstavlja celotno vrstico besedila.
  • $ 1 : predstavlja prvo polje.
  • $ 2 : predstavlja drugo polje.
  • 7 USD : predstavlja sedmo polje.
  • 45 USD : Predstavlja 45. polje.
  • $ NF : pomeni "število polj" in predstavlja zadnje polje.

Za prikaz majhne besedilne datoteke, ki vsebuje kratek citat, pripisan Dennisu Ritchieju, vtipkamo naslednje:

mačka dennis_ritchie.txt

Natisniti želimo  awkprvo, drugo in zadnje polje ponudbe. Upoštevajte, da čeprav je ovito v oknu terminala, gre le za eno vrstico besedila.

Vtipkamo naslednji ukaz:

awk '{print $ 1, $ 2, $ NF}' dennis_ritchie.txt

Te preprostosti ne poznamo. je 18. polje v vrstici besedila in nam je vseeno. Vemo, da je zadnje polje in lahko uporabimo $NFnjegovo vrednost. Obdobje se šteje le za še en lik v telesu polja.

Dodajanje ločevalnikov izhodnih polj

Lahko tudi naročite, awknaj med polji natisne določen znak namesto privzetega presledka. Privzeti izhod iz  dateukaza je nekoliko nenavaden, ker je čas vstavljen ravno sredi njega. Lahko pa vtipkamo naslednje in awkz njimi izvlečemo polja, ki jih želimo:

datum
datum | awk '{natisni $ 2, $ 3, $ 6}'

S OFS spremenljivko (ločilo izhodnega polja) bomo uporabili ločilo med mesecem, dnevom in letom. Upoštevajte, da spodaj ukaz zapišemo v enojne narekovaje ( ') in ne v zavite oklepaje ( {}):

datum | awk 'OFS = "/" {natisni $ 2, $ 3, $ 6}'
datum | awk 'OFS = "-" {natisni $ 2, $ 3, $ 6}'

Pravila BEGIN in END

BEGINPravilo se izvede enkrat pred vsemi začetkom obdelave besedila. Pravzaprav se izvede, awk še preden prebere besedilo. ENDPravilo se izvede po tem, ko so vsa obdelava končana. Lahko jih imate več BEGIN in  ENDpravila, ki se bodo izvajala po vrstnem redu.

Za naš primer BEGINpravila bomo natisnili celoten citat iz dennis_ritchie.txtdatoteke, ki smo jo prej uporabili, z naslovom nad njo.

Za to vtipkamo ta ukaz:

awk 'BEGIN {print "Dennis Ritchie"} {print $0}' dennis_ritchie.txt

Note the BEGIN rule has its own set of actions enclosed within its own set of curly braces ({}).

We can use this same technique with the command we used previously to pipe output from who into awk. To do so, we type the following:

who | awk 'BEGIN {print "Active Sessions"} {print $1,$4}'

Input Field Separators

If you want awk to work with text that doesn’t use whitespace to separate fields, you have to tell it which character the text uses as the field separator. For example, the /etc/passwd file uses a colon (:) to separate fields.

We’ll use that file and the -F (separator string) option to tell awk to use the colon (:) as the separator. We type the following to tell awk to print the name of the user account and the home folder:

awk -F: '{print $1,$6}' /etc/passwd

The output contains the name of the user account (or application or daemon name) and the home folder (or the location of the application).

Adding Patterns

If all we’re interested in are regular user accounts, we can include a pattern with our print action to filter out all other entries. Because User ID numbers are equal to, or greater than, 1,000, we can base our filter on that information.

We type the following to execute our print action only when the third field ($3) contains a value of 1,000 or greater:

awk -F: '$3 >= 1000 {print $1,$6}' /etc/passwd

The pattern should immediately precede the action with which it’s associated.

We can use the BEGIN rule to provide a title for our little report. We type the following, using the (\n) notation to insert a newline character into the title string:

awk -F: 'BEGIN {print "User Accounts\n-------------"} $3 >= 1000 {print $1,$6}' /etc/passwd

Patterns are full-fledged regular expressions, and they’re one of the glories of awk.

Let’s say we want to see the universally unique identifiers (UUIDs) of the mounted file systems. If we search through the /etc/fstab file for occurrences of the string “UUID,” it ought to return that information for us.

We use the search pattern “/UUID/” in our command:

awk '/UUID/ {print $0}' /etc/fstab

It finds all occurrences of “UUID” and prints those lines. We actually would’ve gotten the same result without the print action because the default action prints the entire line of text. For clarity, though, it’s often useful to be explicit. When you look through a script or your history file, you’ll be glad you left clues for yourself.

The first line found was a comment line, and although the “UUID” string is in the middle of it, awk still found it. We can tweak the regular expression and tell awk to process only lines that start with “UUID.” To do so, we type the following which includes the start of line token (^):

awk '/^UUID/ {print $0}' /etc/fstab

That’s better! Now, we only see genuine mount instructions. To refine the output even further, we type the following and restrict the display to the first field:

awk '/^UUID/ {print $1}' /etc/fstab

If we had multiple file systems mounted on this machine, we’d get a neat table of their UUIDs.

Built-In Functions

awk has many functions you can call and use in your own programs, both from the command line and in scripts. If you do some digging, you’ll find it very fruitful.

To demonstrate the general technique to call a function, we’ll look at some numeric ones. For example, the following prints the square root of 625:

awk 'BEGIN { print sqrt(625)}'

This command prints the arctangent of 0 (zero) and -1 (which happens to be the mathematical constant, pi):

awk 'BEGIN {print atan2(0, -1)}'

In the following command, we modify the result of the atan2() function before we print it:

awk 'BEGIN {print atan2(0, -1)*100}'

Functions can accept expressions as parameters. For example, here’s a convoluted way to ask for the square root of 25:

awk 'BEGIN { print sqrt((2+3)*5)}'

awk Scripts

If your command line gets complicated, or you develop a routine you know you’ll want to use again, you can transfer your awk command into a script.

In our example script, we’re going to do all of the following:

  • Tell the shell which executable to use to run the script.
  • Prepare awk to use the FS field separator variable to read input text with fields separated by colons (:).
  • Use the OFS output field separator to tell awk to use colons (:) to separate fields in the output.
  • Set a counter to 0 (zero).
  • Set the second field of each line of text to a blank value (it’s always an “x,” so we don’t need to see it).
  • Print the line with the modified second field.
  • Increment the counter.
  • Print the value of the counter.

Our script is shown below.

The BEGIN rule carries out the preparatory steps, while the END rule displays the counter value. The middle rule (which has no name, nor pattern so it matches every line) modifies the second field, prints the line, and increments the counter.

The first line of the script tells the shell which executable to use (awk, in our example) to run the script. It also passes the -f (filename) option to awk, which informs it the text it’s going to process will come from a file. We’ll pass the filename to the script when we run it.

We’ve included the script below as text so you can cut and paste:

#!/usr/bin/awk -f  BEGIN { # set the input and output field separators FS=":" OFS=":" # zero the accounts counter accounts=0 } { # set field 2 to nothing $2="" # print the entire line print $0 # count another account accounts++ } END { # print the results print accounts " accounts.\n" }

Save this in a file called omit.awk. To make the script executable, we type the following using chmod:

chmod +x omit.awk

Now, we’ll run it and pass the /etc/passwd file to the script. This is the file awk will process for us, using the rules within the script:

./omit.awk /etc/passwd

The file is processed and each line is displayed, as shown below.

The “x” entries in the second field were removed, but note the field separators are still present. The lines are counted and the total is given at the bottom of the output.

awk Doesn’t Stand for Awkward

awk doesn’t stand for awkward; it stands for elegance. It’s been described as a processing filter and a report writer. More accurately, it’s both of these, or, rather, a tool you can use for both of these tasks. In just a few lines, awk achieves what requires extensive coding in a traditional language.

To moč izkorišča preprost koncept pravil, ki vsebujejo vzorce, ki izbirajo besedilo za obdelavo in dejanja, ki opredeljujejo obdelavo.