Cara Menggunakan Perintah awk di Linux

Di Linux,  awkadalah dinamo manipulasi teks baris perintah, serta bahasa skrip yang kuat. Berikut adalah pengenalan kepada beberapa ciri yang paling menarik.

Betapa awk Mendapat Namanya

The  awk arahan dinamakan menggunakan singkatan daripada tiga orang yang menulis versi asal pada tahun 1977: Alfred Aho, Peter Weinberger, dan Brian Kernighan. Ketiga-tiga lelaki ini berasal dari AT&T Bell Laboratories Unix pantheon. Dengan sumbangan banyak orang lain sejak itu, awk terus berkembang.

Ini adalah bahasa skrip penuh, serta kit alat manipulasi teks lengkap untuk baris perintah. Sekiranya artikel ini memenuhi selera anda, anda boleh melihat setiap perincian  awk dan fungsinya.

Peraturan, Corak, dan Tindakan

awkberfungsi pada program yang mengandungi peraturan yang terdiri daripada corak dan tindakan. Tindakan dijalankan pada teks yang sesuai dengan corak. Corak ditutup dengan pendakap kerinting ( {}). Bersama-sama, corak dan tindakan membentuk peraturan. Keseluruhan awkprogram ini dilampirkan dalam petikan tunggal ( ').

Mari lihat jenis awkprogram yang paling mudah . Ia tidak mempunyai corak, sehingga sesuai dengan setiap baris teks yang dimasukkan ke dalamnya. Ini bererti tindakan itu dilakukan pada setiap baris. Kami akan menggunakannya pada output dari whoarahan.

Berikut adalah output standard dari who:

who

Mungkin kita tidak memerlukan semua maklumat itu, tetapi, hanya mahu melihat nama-nama di akaun. Kami dapat whomemasukkan output dari dalam awk, dan kemudian memberitahu awkuntuk mencetak hanya bidang pertama.

Secara lalai, awkmenganggap medan sebagai rentetan watak yang dikelilingi oleh ruang kosong, permulaan garis, atau akhir baris. Bidang dikenal pasti dengan tanda dolar ( $) dan nombor. Jadi,  $1mewakili bidang pertama, yang akan kita gunakan dengan print tindakan untuk mencetak bidang pertama.

Kami menaip perkara berikut:

siapa | awk '{cetak $ 1}'

awk mencetak medan pertama dan membuang sisa baris.

Kami boleh mencetak seberapa banyak bidang yang kami mahu. Sekiranya kita menambahkan koma sebagai pemisah,  awkmencetak ruang di antara setiap medan.

Kami taipkan yang berikut untuk mencetak masa orang masuk (medan empat):

siapa | awk '{cetak $ 1, $ 4}'

Terdapat beberapa pengecam bidang khas. Ini mewakili keseluruhan baris teks dan bidang terakhir dalam baris teks:

  • $ 0 : Mewakili keseluruhan baris teks.
  • $ 1 : Merupakan bidang pertama.
  • $ 2 : Mewakili bidang kedua.
  • $ 7 : Mewakili bidang ketujuh.
  • $ 45 : Merupakan bidang ke-45.
  • $ NF : bermaksud "bilangan medan", dan mewakili bidang terakhir.

Kami akan menaip yang berikut untuk memunculkan fail teks kecil yang mengandungi petikan pendek yang dikaitkan dengan Dennis Ritchie:

kucing dennis_ritchie.txt

Kami ingin  awkmencetak petikan bidang pertama, kedua, dan terakhir. Perhatikan bahawa walaupun dibungkus di tetingkap terminal, itu hanya satu baris teks.

Kami menaip arahan berikut:

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

Kami tidak tahu bahawa "kesederhanaan." adalah bidang ke-18 dalam baris teks, dan kami tidak peduli. Yang kita tahu adalah bidang terakhir, dan kita boleh gunakan $NFuntuk mendapatkan nilainya. Tempoh itu hanya dianggap watak lain dalam badan bidang.

Menambah Pemisah Medan Keluaran

Anda juga boleh memberitahu awkuntuk mencetak watak tertentu antara medan dan bukannya watak ruang lalai. Output lalai dari  dateperintah itu agak pelik kerana waktunya dijadualkan tepat di tengahnya. Walau bagaimanapun, kita boleh menaip yang berikut dan menggunakan awkuntuk mengekstrak bidang yang kita mahukan:

Tarikh
tarikh | awk '{cetak $ 2, $ 3, $ 6}'

Kami akan menggunakan OFS pemboleh ubah (output field separator) untuk meletakkan pemisah antara bulan, hari, dan tahun. Perhatikan bahawa di bawah ini kita sertakan perintah dalam tanda kutip tunggal ( '), bukan pendakap keriting ( {}):

tarikh | awk 'OFS = "/" {cetak $ 2, $ 3, $ 6}'
tarikh | awk 'OFS = "-" {cetak $ 2, $ 3, $ 6}'

Peraturan BEGIN dan TAMAT

A BEGINperaturan dilaksanakan sekali sebelum sebarang pemprosesan teks bermula. Sebenarnya, ia dilaksanakan sebelum awk membaca teks. Satu ENDperaturan dilaksanakan selepas semua pemprosesan telah selesai. Anda boleh mempunyai banyak BEGIN dan  ENDperaturan, dan peraturan tersebut akan dilaksanakan dengan teratur.

Untuk contoh BEGINperaturan kami, kami akan mencetak keseluruhan petikan dari dennis_ritchie.txtfail yang kami gunakan sebelumnya dengan tajuk di atasnya.

Untuk melakukannya, kami menaip arahan ini:

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.

That power is harnessed by the simple concept of rules that contain patterns, that select the text to process, and actions that define the processing.