我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
我有一个~23000行的SQL转储,其中包含几个数据库的数据价值。我需要提取这个文件的某个部分(即单个数据库的数据),并将其放在一个新文件中。我知道我想要的数据的开始行号和结束行号。
谁知道一个Unix命令(或一系列命令)可以从文件中提取16224到16482行之间的所有行,然后将它们重定向到一个新文件中?
当前回答
您可以使用'vi',然后使用以下命令:
:16224,16482w!/tmp/some-file
另外:
cat file | head -n 16482 | tail -n 258
编辑:-只是补充解释,您使用head -n 16482显示前16482行,然后使用tail -n 258显示第一次输出的最后258行。
其他回答
我正准备发布头部/尾部技巧,但实际上我可能只是启动emacs。: -)
Esc-x goto-line ret 16224 马克(ctrl-space) Esc-x goto-line ret 16482 esc-w
打开新的输出文件ctl-y 保存
让我看看发生了什么。
也许,你会给这个简陋的脚本一个机会;-)
#!/usr/bin/bash
# Usage:
# body n m|-m
from=$1
to=$2
if [ $to -gt 0 ]; then
# count $from the begin of the file $to selected line
awk "NR >= $from && NR <= $to {print}"
else
# count $from the begin of the file skipping tailing $to lines
awk '
BEGIN {lines=0; from='$from'; to='$to'}
{++lines}
NR >= $from {line[lines]=$0}
END {for (i = from; i < lines + to + 1; i++) {
print line[i]
}
}'
fi
输出:
$ seq 20 | ./body.sh 5 15
5
6
7
8
9
10
11
12
13
14
15
$ seq 20 | ./body.sh 5 -5
5
6
7
8
9
10
11
12
13
14
15
在这种情况下,您可以使用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
使用head/tail非常简单:
head -16482 in.sql | tail -258 > out.sql
使用sed:
sed -n '16224,16482p' in.sql > out.sql
使用awk:
awk 'NR>=16224&&NR<=16482' in.sql > out.sql
我写了一个叫做splitter的Haskell程序,它就是这样做的:阅读我发布的博客文章。
您可以使用该程序如下:
$ cat somefile | splitter 16224-16482
这就是它的全部。您将需要Haskell来安装它。只是:
$ cabal install splitter
这样就做完了。我希望这个程序对您有用。