我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
当前回答
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脚本中的地址可以是以下任何一种形式: 数量 指定行号将只匹配输入中的该行。 一个地址范围可以通过指定两个地址来指定 用逗号(,)分隔。地址范围匹配从 第一个地址匹配,并一直持续到第二个 地址匹配(包括)。
其他回答
接受答案中的-n起作用。如果你有兴趣的话,还有另一种方法。
cat $filename | sed "${linenum}p;d";
它的作用如下:
管道插入文件的内容(或根据需要输入文本)。 Sed选择给定的行,打印它 D必须删除行,否则sed将假定最终打印所有行。也就是说,如果没有d,你将得到被选中行打印的所有行打印两次,因为你有${linenum}p部分要求打印它。我很确定-n和这里的d是一样的。
这可能为你工作(GNU sed):
sed -ne '16224,16482w newfile' -e '16482q' file
或者利用bash:
sed -n $'16224,16482w newfile\n16482q' file
perl -ne 'print if 16224..16482' file.txt > new_file.txt
我想从一个使用变量的脚本中做同样的事情,并通过在$变量周围加上引号来分隔变量名和p来实现:
sed -n "$first","$count"p imagelist.txt >"$imageblock"
我想把一个列表分成不同的文件夹,找到最初的问题和答案,这是一个有用的步骤。(分裂命令不是旧操作系统上的选项,我必须将代码移植到)。
cat dump.txt | head -16224 | tail -258
应该能行。这种方法的缺点是,您需要做算术来确定tail的参数,并考虑是否希望“between”包含结束行。