如果我明白你希望正確地提取線,也可以實現使用bash內建(參數擴展/子串提取)相同:
#!/bin/bash
## read from "$1" or stdin
[ -r "$1" ] && infile="$1" || infile=/dev/stdin
## check line beginnings for each line
while read -r line; do
[ "${line%%:*}" = "Wake Locks" -o \
"${line%% *}" = "WAKELOCK_NAME" -o \
"${line%% *}" = "ANOTHER_WAKELOCK" -o \
"${line%% *}" = "WAKELOCK_NAME" ] && echo "$line"
done < "$infile"
exit 0
或者用grep
可以使用文件包含圖形你想在你的大文件中匹配並致電grep -f matchfile largefile
。在這種情況下的matchfile可能看起來像:
grep的模式文件
$ cat dat/wakematch.txt
^Wake Locks:
^WAKELOCK_NAME
^ANOTHER_WAKELOCK
^WAKELOCK_NAME
測試輸入
$ cat dat/wake.txt
junk and more junk
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
WAKELOCK 'Term' (uid=35647, pid=362505, ws=null)
#White space
junk and more junk
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
WAKELOCK 'Term' (uid=35647, pid=362505, ws=null)
#White space
使用/輸出 - bash的參數擴展/子串提取
$ bash wakelock.sh dat/wake.txt
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
$ bash wakelock.sh <dat/wake.txt
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
使用grep
$ grep -f dat/wakematch.txt dat/wake.txt
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
Wake Locks: size=3
WAKELOCK_NAME 'Term' (uid=93847, pid=364345, ws=null)
ANOTHER_WAKELOCK 'Term' (uid=9190247, pid=323345, ws=null)
有三個的PID你展示線。你想要哪一個?或者,你想要所有? – John1024
每行有一個pid,所以他們都是 – BonBon