Shell-Script

如何從以下作為命令輸出的字元串中提取數字?

  • September 6, 2018

我想提取我們在執行命令時得到的消息號mailx -H。我只想要未讀和新消息的消息號。我嘗試使用以下命令:

mailx -H|grep '^ [UN]'|cut -c 3-

但它沒有給出所需的輸出。它給出了 U 或 N 之後的整行。 mailx -H 命令的範例輸出是:

O 95 abcd Thu Sep  6 20:29   25/1245  Incident: 00291
O 96 efgh Thu Sep  6 20:29   25/1245  Incident: 00291
O 97 abcd  Thu Sep  6 20:29   25/1245 Incident: 00291
O 98 pqrs Thu Sep  6 20:29   25/1245  Incident: 00291
O 99 abcd  Thu Sep  6 20:29   25/1245 Incident: 00291
U100 cnhn Thu Sep  6 20:29   25/1244  Incident: 00291
U101 gont Thu Sep  6 20:29   25/1244  Incident: 00291
U102 qwer Thu Sep  6 20:29   25/1244  Incident: 00291

我想要 U 或 N 之後的數字,即新消息或未讀消息和 O(舊)消息。如何在 shell 腳本中做到這一點?預期的輸出是

95
96
97
98
99
100
101
102

試試這個,

mailx -H | nawk -F '[^0-9]+' '/^ [U|N]/ { print $2}' 
  • [^0-9]+作為FS。
  • 提取以U或開頭的行N
  • 列印第二個欄位

試試這個grep

grep -P -o '(?<=O|U|N) ?[0-9]+'

例子:

echo "O 95 abcd Thu Sep  6 20:29   25/1245  Incident: 00291
O 96 efgh Thu Sep  6 20:29   25/1245  Incident: 00291
O 97 abcd  Thu Sep  6 20:29   25/1245 Incident: 00291
O 98 pqrs Thu Sep  6 20:29   25/1245  Incident: 00291
O 99 abcd  Thu Sep  6 20:29   25/1245 Incident: 00291
U100 cnhn Thu Sep  6 20:29   25/1244  Incident: 00291
U101 gont Thu Sep  6 20:29   25/1244  Incident: 00291
U102 qwer Thu Sep  6 20:29   25/1244  Incident: 00291" | grep -P -o '(?<=O|U|N) ?[0-9]+'
95
96
97
98
99
100
101
102
grep --version
grep (GNU grep) 2.27

如果grep上述方法不起作用/不夠,請嘗試以下操作sed

sed -E 's/^(O|U|N) ?([0-9]+) .*/\2/g'

例子:

echo "O 95 abcd Thu Sep  6 20:29   25/1245  Incident: 00291
O 96 efgh Thu Sep  6 20:29   25/1245  Incident: 00291
O 97 abcd  Thu Sep  6 20:29   25/1245 Incident: 00291
O 98 pqrs Thu Sep  6 20:29   25/1245  Incident: 00291
O 99 abcd  Thu Sep  6 20:29   25/1245 Incident: 00291
U100 cnhn Thu Sep  6 20:29   25/1244  Incident: 00291
U101 gont Thu Sep  6 20:29   25/1244  Incident: 00291
U102 qwer Thu Sep  6 20:29   25/1244  Incident: 00291" | sed -E 's/^(O|U|N) ?([0-9]+) .*/\2/g'
95
96
97
98
99
100
101
102

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