Text-Processing

使用 grep/awk 在文本文件中查找/列印特定值

  • January 28, 2022

假設我有一個包含以下 5 行的文本文件:

Tue 18 2022 car model: Toyota , car motor: 2001 , car color: blue , year of production: 2018
Thu 19 2022 car model: Mercedes , car color: black , year of production: 2012 , car motor: 4000
Thu 20 2022 used: yes , car motor: 1999 , car model: Mercedes , car color: black , year of production: 2012
Thu 20 2022 car model: Kia , car motor: 1500 , car color: red , used: no , year of production: 2010
Thu 20 2022 price: 150, car model: GMC  , car color: purple , car motor: 3500 , year of production: 2010

我正在尋找 grep/awk(或 freebsd 11 上可用的其他實用程序),它將查找/列印以下條件評估為 TRUE 的每一行:

Phrase "car motor:" followed by a space and then a numerical value greater than 2000

此類 grep/awk 應從文本文件中查找/列印以下行:

Tue 18 2022 car model: Toyota , car motor: 2001 , car color: blue , year of production: 2018
Thu 19 2022 car model: Mercedes , car color: black , year of production: 2012 , car motor: 4000
Thu 20 2022 price: 150, car model: GMC  , car color: purple , car motor: 3500 , year of production: 2010

我認為 perl 將在 freebsd 上可用,並且您的要求可以直接轉化為:

perl -ne 'print if /car motor: (\d+)/ and $1 > 2000' file

使用 GNU awk 將第三個參數匹配():

$ awk 'match($0,/car motor: ([0-9]+)/,a) && (a[1] > 2000)' file
Tue 18 2022 car model: Toyota , car motor: 2001 , car color: blue , year of production: 2018
Thu 19 2022 car model: Mercedes , car color: black , year of production: 2012 , car motor: 4000
Thu 20 2022 price: 150, car model: GMC  , car color: purple , car motor: 3500 , year of production: 2010

或使用任何 awk:

$ awk 'match($0,/car motor: [0-9]+/) && (substr($0,RSTART+11) > 2000)' file
Tue 18 2022 car model: Toyota , car motor: 2001 , car color: blue , year of production: 2018
Thu 19 2022 car model: Mercedes , car color: black , year of production: 2012 , car motor: 4000
Thu 20 2022 price: 150, car model: GMC  , car color: purple , car motor: 3500 , year of production: 2010

或者也可以使用任何 awk 但更神秘一點:

$ awk '{k=$0} sub(/.*car motor: /,"",k) && (k > 2000)' file
Tue 18 2022 car model: Toyota , car motor: 2001 , car color: blue , year of production: 2018
Thu 19 2022 car model: Mercedes , car color: black , year of production: 2012 , car motor: 4000
Thu 20 2022 price: 150, car model: GMC  , car color: purple , car motor: 3500 , year of production: 2010

引用自:https://unix.stackexchange.com/questions/687108