如果我理解您希望正确提取的行,您也可以使用 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。在这种情况下,匹配文件可能如下所示:
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)