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

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


当前回答

又快又脏:

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

可能不是最好的方法,但应该有用。

顺便说一下:259 = 16482-16224+1。

其他回答

又快又脏:

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

可能不是最好的方法,但应该有用。

顺便说一下:259 = 16482-16224+1。

在这种情况下,您可以使用sed命令,它非常快。

如前所述,让我们假设范围是:在16224和16482行之间

#get the lines from 16224 to 16482 and prints the values into filename.txt file
        sed -n '16224 ,16482p' file.txt > filename.txt 
    
#Additional Info to showcase other possible scenarios:
    
#get the 16224 th line and writes the value to filename.txt

        sed -n '16224p' file.txt > filename.txt 

#get the 16224 and 16300 line values only and write to filename.txt. 

        sed -n '16224p;16300p;' file.txt > filename.txt

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

我的文件比较大 对于{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
sed -n '16224,16482 p' orig-data-file > new-file

其中16224、16482是起始行号和结束行号,包括。这是1索引。-n抑制将输入回显为输出,这显然不是你想要的;数字表示要执行以下命令的行范围;命令p输出相关的行。

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