如何从Unix上的文本文件中提取预定范围的行?

时间:2020-03-05 18:58:55  来源:igfitidea点击:

我有一个〜23000行的SQL转储,其中包含几个数据库值的数据。我需要提取此文件的特定部分(即单个数据库的数据)并将其放置在新文件中。我知道我想要的数据的开始和结束行号。

有谁知道Unix命令(或者一系列命令)从文件中提取16224和16482行之间的所有行,然后将它们重定向到新文件中?

解决方案

回答

我们可以使用" vi",然后使用以下命令:

:16224,16482w!/tmp/some-file

或者:

cat file | head -n 16482 | tail -n 258

编辑:只需添加说明,我们就可以使用head -n 16482显示前16482行,然后使用tail -n 258从第一个输出中获取最后258行。

回答

sed -n '16224,16482p;16483q' filename > newfile

从sed手册中:

p - 
      Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.
  
  n -
      If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If
  there is no more input then sed exits without processing any more
  commands.
  
  q -
  Exit sed without processing any more commands or input.
  Note that the current pattern space is printed if auto-print is not disabled with the -n option.

Addresses in a sed script can be in any of the following forms:
  
  number
      Specifying a line number will match only that line in the input.
  
  An address range can be specified by specifying two addresses
  separated by a comma (,). An address range matches lines starting from
  where the first address matches, and continues until the second
  address matches (inclusively).

回答

# print section of file based on line numbers
 sed -n '16224 ,16482p'               # method 1
 sed '16224,16482!d'                 # method 2

回答

perl -ne 'print if 16224..16482' file.txt > new_file.txt

回答

快速而肮脏:

head -16428 < file.in | tail -259 > file.out

可能不是最好的方法,但它应该可以工作。

顺便说一句:259 = 16482-16224 + 1.

回答

sed -n'16224,16482p'<dump.sql`

回答

使用头/尾非常简单:

head -16482 in.sql | tail -258 > out.sql

使用sed:

sed -n '16482,16482p' in.sql > out.sql

使用awk:

awk 'NR>=10&&NR<=20' in.sql > out.sql

回答

sed -n '16224,16482 p' orig-data-file > new-file

其中16224,16482是起始行号和结束行号(含)。这是1索引的。 -n禁止将输入作为输出回显,这显然是不希望的。数字表示执行以下命令的行范围;命令" p"打印出相关行。

回答

cat dump.txt | head -16224 | tail -258

应该做到的。这种方法的缺点是,我们需要执行算术运算来确定tail的参数,并考虑是否要在" between"中包含结尾行。

回答

我本来打算发布头尾技巧,但实际上我可能只是启动了emacs。 ;-)

  • esc-x转到行ret16224
  • 标记(ctrl-space)
  • esc-x转到行ret16482
  • esc-w

打开新的输出文件ctl-y

让我看看发生了什么。