我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
当前回答
由于我们讨论的是从文本文件中提取文本行,所以我将给出一个特殊情况,即您希望提取与某个模式匹配的所有行。
myfile content:
=====================
line1 not needed
line2 also discarded
[Data]
first data line
second data line
=====================
sed -n '/Data/,$p' myfile
将打印[Data]行和其余部分。如果想要从第一行到模式的文本,输入:sed -n '1,/Data/p' myfile。此外,如果您知道两个模式(最好在文本中是唯一的),则可以使用匹配指定范围的开始行和结束行。
sed -n '/BEGIN_MARK/,/END_MARK/p' myfile
其他回答
我想从一个使用变量的脚本中做同样的事情,并通过在$变量周围加上引号来分隔变量名和p来实现:
sed -n "$first","$count"p imagelist.txt >"$imageblock"
我想把一个列表分成不同的文件夹,找到最初的问题和答案,这是一个有用的步骤。(分裂命令不是旧操作系统上的选项,我必须将代码移植到)。
我会用:
awk 'FNR >= 16224 && FNR <= 16482' my_file > extracted.txt
FNR包含从文件中读取的行的记录(行)号。
那些想要计算头部、|、尾部组合的间隔的人是想多了。
下面是如何在不计算任何东西的情况下得到“16224 - 16482”范围:
cat file | head -n +16482 | tail -n +16224
解释:
The + instructs the head/tail command to "go up to / start from" (respectively) the specified line number as counted from the beginning of the file. Similarly, a - instructs them to "go up to / start from" (respectively) the specified line number as counted from the end of the file The solution shown above simply uses head first, to 'keep everything up to the top number', and then tail second, to 'keep everything from the bottom number upwards', thus defining our range of interest (with no need to compute an interval).
我们甚至可以在命令行检查:
cat filename|sed 'n1,n2!d' > abc.txt
例如:
cat foo.pl|sed '100,200!d' > abc.txt
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