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

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


当前回答

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
 # print section of file based on line numbers
 sed -n '16224 ,16482p'               # method 1
 sed '16224,16482!d'                 # method 2

在这种情况下,您可以使用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
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脚本中的地址可以是以下任何一种形式: 数量 指定行号将只匹配输入中的该行。 一个地址范围可以通过指定两个地址来指定 用逗号(,)分隔。地址范围匹配从 第一个地址匹配,并一直持续到第二个 地址匹配(包括)。

那些想要计算头部、|、尾部组合的间隔的人是想多了。

下面是如何在不计算任何东西的情况下得到“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).