例如,如果我的 Linux 系统上的文件中有以下文本:
10-02-2020
given as file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
In addition, two variant programs egrep and fgrep are available. egrep is the same as grep -E. fgrep is the same as grep -F
16-02-2020
The top program provides a dynamic real-time view of a running
system. It can display system summary information as well as a list
of processes or threads currently being managed by the Linux kernel.
The types of system summary information shown and the types, order
and size of information displayed for processes are all user
configurable and that configuration can be made persistent across
restarts.
如何删除之前的所有文本16-02-2020
并将文件变成这样:
16-02-2020
The top program provides a dynamic real-time view of a running
system. It can display system summary information as well as a list
of processes or threads currently being managed by the Linux kernel.
The types of system summary information shown and the types, order
and size of information displayed for processes are all user
configurable and that configuration can be made persistent across
restarts.
答案1
您可以使用 来执行此操作sed
。一般格式为:
sed -n '/pattern1/,/pattern2/p' file
除非明确告知,否则不会打印-n
的原因。 Som 该命令将打印位于行匹配和一个匹配(包括)之间的所有行。如果有多个匹配项,将打印多行。sed
p
pattern1
pattern2
就您而言,您希望打印所有内容直到文件末尾,因此pattern2
将是$
.因此,您正在寻找这个:
$ sed -n '/16-02-2020/,$p' file
16-02-2020
The top program provides a dynamic real-time view of a running
system. It can display system summary information as well as a list
of processes or threads currently being managed by the Linux kernel.
The types of system summary information shown and the types, order
and size of information displayed for processes are all user
configurable and that configuration can be made persistent across
restarts.
在不相关的注释中,fgrep
并且egrep
已弃用,您应该使用grep -F
和grep -E
。看man grep
:
此外,变体程序egrep和fgrep分别与grep -E和grep -F相同。这些变体已被弃用,但提供它们是为了向后兼容。
答案2
Perl版本:
perl -ne '$f=1 if /16-02-2020/; print if $f' file
答案3
对于从文件中修剪一个块,我认为ed
,将文件视为一个整体,而不是像这样一次只作用于一行sed
是更好的选择:
$ ed -s input.txt
1,/^16-02-2020/-1d
wq
$ cat input.txt
16-02-2020
The top program provides a dynamic real-time view of a running
system. It can display system summary information as well as a list
of processes or threads currently being managed by the Linux kernel.
The types of system summary information shown and the types, order
and size of information displayed for processes are all user
configurable and that configuration can be made persistent across
restarts.
删除从第一行到以 开头的行之前的所有内容,16-02-2020
并保存修改后的文件。如果在脚本中使用,您可以使用定界文档将命令发送到ed
:
ed -s input.txt <<EOF
1,/^16-02-2020/-1d
w
EOF