我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
当前回答
# print section of file based on line numbers
sed -n '16224 ,16482p' # method 1
sed '16224,16482!d' # method 2
其他回答
又快又脏:
head -16428 < file.in | tail -259 > file.out
可能不是最好的方法,但应该有用。
顺便说一下:259 = 16482-16224+1。
那些想要计算头部、|、尾部组合的间隔的人是想多了。
下面是如何在不计算任何东西的情况下得到“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).
艾德:使用
ed -s infile <<<'16224,16482p'
-s抑制诊断输出;实际的命令在一个here-string中。具体来说,16224,16482p在所需的行地址范围上运行p (print)命令。
我一直在寻找这个问题的答案,但最终我不得不编写自己的代码。以上的答案都不令人满意。 假设您有一个非常大的文件,并且有一些想要打印的行号,但这些行号不是按顺序排列的。您可以执行以下操作:
我的文件比较大 对于{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
由于我们讨论的是从文本文件中提取文本行,所以我将给出一个特殊情况,即您希望提取与某个模式匹配的所有行。
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