9

我有一个 150GB 的大文件 CSV 文件,我想删除前 17 行和最后 8 行。我尝试了以下方法,但似乎无法正常工作

sed -i -n -e :a -e '1,8!{P;N;D;};N;ba' 

sed -i '1,17d' 

我想知道是否有人可以帮助 sed 或 awk,一个班轮会很棒吗?

4

7 回答 7

18

head并且tailsed或更适合这项工作awk

tail -n+18 file | head -n-8 > newfile
于 2013-02-07T13:36:28.777 回答
10
awk -v nr="$(wc -l < file)" 'NR>17 && NR<(nr-8)' file
于 2013-02-07T13:46:02.047 回答
2

所有 awk:

awk 'NR>y+x{print A[NR%y]} {A[NR%y]=$0}' x=17 y=8 file
于 2013-03-08T01:31:14.087 回答
1
Try this :

sed '{[/]<n>|<string>|<regex>[/]}d' <fileName>       
sed '{[/]<adr1>[,<adr2>][/]d' <fileName>

在哪里

  1. /.../=分隔符

  2. n = 行号

  3. string = 在行中找到的字符串

  4. regex = 对应于搜索模式的正则表达式

  5. addr = 行的地址(数字或模式)

  6. d = 删除

参考这个链接

于 2013-02-07T13:37:41.377 回答
0
LENGTH=`wc -l < file`
head -n $((LENGTH-8)) file | tail -n $((LENGTH-17)) > file

编辑:正如 mtk 在评论中发布的那样,这不起作用。如果您想使用wc和跟踪文件长度,您应该使用:

LENGTH=`wc -l < file`
head -n $((LENGTH-8)) file | tail -n $((LENGTH-8-17)) > file

或者:

LENGTH=`wc -l < file`
head -n $((LENGTH-8)) file > file
LENGTH=`wc -l < file`
tail -n $((LENGTH-17)) file > file

是什么让这个解决方案没有 choroba 发布的那么优雅:)

于 2013-02-07T13:37:21.893 回答
0

我今天为 shell 学到了这一点。

{
  ghead -17  > /dev/null
  sed -n -e :a -e '1,8!{P;N;D;};N;ba'
} < my-bigfile > subset-of

必须使用非消费head类,因此使用gheadGNU coreutils。

于 2013-02-07T14:17:33.870 回答
0

类似于雷神的回答,但有点短:

sed -i '' -e $'1,17d;:a\nN;19,25ba\nP;D' file.txt

-i ''告诉 sed 就地编辑文件。(您的系统上的语法可能有点不同。请查看手册页。)

如果front要从前面和tail结尾删除行,则必须使用以下数字:

1,{front}d;:a\nN;{front+2},{front+tail}ba\nP;D

(我在这里把它们放在花括号中,但这只是伪代码。你必须用实际数字替换它们。此外,它应该与 一起使用{front+1},但它不适用于我的机器(macOS 10.12.4)。我认为这是一个错误。)

我将尝试解释该命令的工作原理。这是一个人类可读的版本:

1,17d     # delete lines 1 ... 17, goto start
:a        # define label a
N         # add next line from file to buffer, quit if at end of file
19,25ba   # if line number is 19 ... 25, goto start (label a)
P         # print first line in buffer
D         # delete first line from buffer, go back to start

First we skip 17 lines. That's easy. The rest is tricky, but basically we keep a buffer of eight lines. We only start printing lines when the buffer is full, but we stop printing when we reach the end of the file, so at the end, there are still eight lines left in the buffer that we didn't print - in other words, we deleted them.

于 2017-04-09T23:47:10.277 回答