1

我有一个包含太多行的文件。

它的构造如下:

Text
Text
Text

<--!Important Text begins here-->
important Text
Important Text
Important Text

<--!Important Text ends here -->

Unimportant Text
....

<--!Important Text begins here-->
important Text
Important Text
Important Text

<--!Important Text ends here -->

Unimportant Text
....<--!Important Text begins here-->
important Text
Important Text
Important Text

<--!Important Text ends here -->

Unimportant Text
....

等等。

我怎样才能把重要的部分保存在一个新文件中?我正在使用 Macintosh 的仪表板终端

4

2 回答 2

1

尝试以下操作:

sed -n '/<--!Important Text begins here-->/,/<--!Important Text ends here -->/ p' \
  infile | 
  fgrep -v -e '<--!Important Text begins here-->' \
           -e '<--!Important Text ends here -->' \
   > outfile

注意:假设所有<--!Important Text ...标记都在单独的一行上。

于 2014-02-25T20:04:26.917 回答
1

如果您希望包含标记,那么您可以执行以下操作:

awk '/<--!Important Text begins here-->/,/<--!Important Text ends here -->/' file

如果您希望忽略标记并仅打印它们之间的内容,您可以执行以下操作:

awk '
/<--!Important Text begins here-->/{p=1; next}
/<--!Important Text ends here -->/{p=0}
p' file

第一个解决方案是一个regex范围。它告诉awk打印范围(包括)之间的所有内容。要忽略标记,您只需要设置和取消设置标志。

于 2014-02-25T20:34:22.527 回答