linux中awk 比較操作符的用法

來源:互聯網
上載者:User


對於 使用 awk 命令的使用者來說,處理一行文本中的數字或者字串時,使用比較子來過濾文本和字串是十分方便的。

在 awk 系列的此部分中,我們將探討一下如何使用比較子來過濾文本或者字串。如果你是程式員,那麼你應該已經熟悉了比較子;對於其它人,下面的部分將介紹比較子。

awk 中的比較子是什嗎?

awk 中的比較子用於比較字串和或者數值,包括以下類型:

> – 大於
< – 小於
>= – 大於等於
<= – 小於等於
== – 等於
!= – 不等於
some_value ~ / pattern/ – 如果 some_value 匹配模式 pattern,則返回 true
some_value !~ / pattern/ – 如果 some_value 不匹配模式 pattern,則返回 true
現在我們通過例子來熟悉 awk 中各種不同的比較子。

在這個例子中,我們有一個檔案名稱為 food_list.txt 的檔案,裡麵包括不同食物的購買列表。我想給食物數量小於或等於 30 的物品所在行的後面加上(**)

File – food_list.txt
No      Item_Name               Quantity        Price
1       Mangoes                    45           $3.45
2       Apples                     25           $2.45
3       Pineapples                 5            $4.45
4       Tomatoes                   25           $3.45
5       Onions                     15           $1.45
6       Bananas                    30           $3.45

Awk 中使用比較子的通用文法如下:

# 運算式 { 動作; }

為了實現剛才的目的,執行下面的命令:

# awk '$3 <= 30 { printf "%s\t%s\n", $0,"**" ; } $3 > 30 { print $0 ;}' food_list.txt
No  Item_Name`      Quantity    Price
1   Mangoes            45       $3.45
2   Apples             25       $2.45   **
3   Pineapples         5        $4.45   **
4   Tomatoes           25       $3.45   **
5   Onions             15       $1.45   **
6   Bananas            30       $3.45   **

在剛才的例子中,發生如下兩件重要的事情:

第一個“運算式 {動作;}”組合中, $3 <= 30 { printf “%s\t%s\n”, $0,”**” ; } 列印出數量小於等於30的行,並且在後面增加(**)。物品的數量是通過 $3 這個域變數獲得的。
第二個“運算式 {動作;}”組合中, $3 > 30 { print $0 ;} 原樣輸出數量小於等於 30 的行。
再舉一個例子:

# awk '$3 <= 20 { printf "%s\t%s\n", $0,"TRUE" ; } $3 > 20  { print $0 ;} ' food_list.txt
No    Item_Name     Quantity    Price
1     Mangoes          45       $3.45
2     Apples           25       $2.45
3     Pineapples        5       $4.45 TRUE
4     Tomatoes         25       $3.45
5     Onions           15       $1.45 TRUE
6     Bananas          30       $3.45

在這個例子中,我們想通過在行的末尾增加 (TRUE) 來標記數量小於等於20的行。

總結

這是一篇對 awk 中的比較子介紹性的指引,因此你需要嘗試其他選項,發現更多使用方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.