Linux

如何在 linux 中從文件中輸出字元串和萬用字元?

  • January 31, 2020

所以我有一個日誌/文本文件。在那個文件中有一堆資訊,但我只想得到一個特定的字元串。

@@204,clientDisconnect,"apMac"="60:d0:2c:3a:f2:60","clientMac"="8c:45:00:84:e8:98","ssid"="Th","userId"="","wlanId"="240","iface"="wlan32","tenantU,19",,"userName"="d","vlanId"="512","radio"="a/n/ac","encryption"="WPA2-AES","osType"="Android","hostname"="Galaxy-S9","firstAuth"="1580412687","associationTime"="1580411444","ipAssignTime"="1580412688","disconnectTime"="1580412724","sessionDuration"="37","disconnectReason"="8","rxFrames"="26","rxBytes"="4415","txFrames"="93","txBytes"="22693","peakRx"="4415","peakTx"="22693","rssi"="62","receivedSignalStrength"="-43","Instantaneous

我只想要disconnectReason = "8". 但是該斷開連接號碼可能會根據客戶端斷開連接的原因而改變。我不確定如何搜尋文件並且只輸出帶有萬用字元的字元串。

我希望它輸出:

disconnectReason ="8"
disconnectReason ="3"
disconnectReason ="1" etc.....

根據您所說的,這應該足以滿足您的需求:

grep -oE '"disconnectReason"="[0-9]+"' yourfile

-o告訴grep只返回字元串的匹配部分

假設您給出的範例是文件中的一行,您可以使用sed刪除您所關注的欄位之前和之後的所有內容:

sed -E 's/.*,("disconnectReason"="[0-9]+"),.*/\1/' <file>

這通過使用帶括號的子表達式“記住”您感興趣的欄位和值,然後使用\1引用第一個(並且僅在這種情況下)記住的子表達式來替換 while 行。

如果您真的堅持要刪除 周圍的雙引號disconnectReason,我會使用另一個 sed 過濾器來做到這一點,而不是使正則表達式複雜化。它可能效率較低,但更容易閱讀:

sed -E 's/.*,("disconnectReason"="[0-9]+"),.*/\1/' <file> |
  sed -E 's/"(disconnectReason)"/\1/'

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