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

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


当前回答

我写了一个叫做splitter的Haskell程序,它就是这样做的:阅读我发布的博客文章。

您可以使用该程序如下:

$ cat somefile | splitter 16224-16482

这就是它的全部。您将需要Haskell来安装它。只是:

$ cabal install splitter

这样就做完了。我希望这个程序对您有用。

其他回答

您可以使用'vi',然后使用以下命令:

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

另外:

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

编辑:-只是补充解释,您使用head -n 16482显示前16482行,然后使用tail -n 258显示第一次输出的最后258行。

我一直在寻找这个问题的答案,但最终我不得不编写自己的代码。以上的答案都不令人满意。 假设您有一个非常大的文件,并且有一些想要打印的行号,但这些行号不是按顺序排列的。您可以执行以下操作:

我的文件比较大 对于{a..k};执行echo $letter;完成| cat -n > myfile.txt

 1  a
 2  b
 3  c
 4  d
 5  e
 6  f
 7  g
 8  h
 9  i
10  j
11  k

我想要的具体行号: shuf -i 1-11 -n 4 > line_numbers_I_want.txt

 10
 11
 4
 9

要打印这些行号,请执行以下操作。 awk ` {system("head myfile.txt -n " $0 " | tail -n 1")} ` line_numbers_I_want.txt

上面所做的是头n行,然后采取最后一行使用尾巴

如果您希望行号按顺序排列,首先sort (is -n numeric sort),然后获取行。

cat line_numbers_I_want.txt | sort -n | awk '{system("head myfile.txt -n " $0 " | tail -n 1")}'

 4  d
 9  i
10  j
11  k

awk还有另一种方法:

awk 'NR==16224, NR==16482' file

如果文件很大,最好在读取最后一行之后退出。这样,它就不会不必要地读取以下行:

awk 'NR==16224, NR==16482-1; NR==16482 {print; exit}' file

awk 'NR==16224, NR==16482; NR==16482 {exit}' file

使用ruby:

ruby -ne 'puts "#{$.}: #{$_}" if $. >= 32613500 && $. <= 32614500' < GND.rdf > GND.extract.rdf
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.

and

sed脚本中的地址可以是以下任何一种形式: 数量 指定行号将只匹配输入中的该行。 一个地址范围可以通过指定两个地址来指定 用逗号(,)分隔。地址范围匹配从 第一个地址匹配,并一直持续到第二个 地址匹配(包括)。