使用UNIX的哪个简单快捷的命令可以打印出从最后一个匹配的模式到文件末尾的所有行?
这个sed命令从第一个出现的位置开始打印。
sed -n '/pattern/,$p' file
这个sed命令从第一个出现的位置开始打印。
sed 'H;/pattern/h;$!d;x;//!d' file
awk '{x=x ORS $0};/pattern/{x=$0};END{if(x ~ //)print x}' file
tac file | sed '/pattern/q' | tac
反转文件,打印直到第一个模式出现,然后退出并再次反转文件。
tac file | awk '/pattern/{print;exit}1' | tac
以下是一种使用Perl的方法:
perl -ne '$seen = 1, @a = () if /pattern/; push @a, $_; END { print @a if $seen }' file
最简单的解决方案就是对整个文件进行正则匹配:
perl -0777 -ne 'print $1 if /pattern(.*?)$/' file
一个独立的awk:
awk '/pattern/{delete a;c=0}{a[c++]=$0}END{for (i=0;i<c;i++){print a[i]}}' file
这是一个纯粹的 awk
awk 'FNR==NR {if ($0~/pattern/) f=FNR;next} FNR==f {a=1}a' file{,}
它会读取文件两次,第一次设置一个标志来记录上次找到的pattern
,然后打印出pattern
和输出。
或者您可以像这样将数据存储在数组中:
awk '/pattern/ {f=NR} {a[NR]=$0} END {for (i=f;i<=NR;i++) print a[i]}' file
使用GNU awk进行多字符RS和gensub():
$ awk -v RS='^$' -v ORS= '{print gensub(/.*(pattern)/,"\\1","")}' file
e.g.:
$ cat file
a
b
c
b
d
$ awk -v RS='^$' -v ORS= '{print gensub(/.*(b)/,"\\1","")}' file
b
d
上面的代码从文件开头删除到最后一个 "b" 的前一个字符。