我如何每四行打印一行

How I can print line every four lines

我有一个包含 8000 行的文件,我想打印第 1,4,8,12,...,7996 行。

我试过这个代码

for j in {1 .. 8000}
do
k= $((4 * $j))
print k 
sed -n $k P test.dat >> test.dat1 
done

但是出现这个错误:

./test.csh: line 3: 4 * {1: syntax error: operand expected (error token is "{1")

这是什么问题,我该怎么做?

使用awk命令:

awk 'NR%4==1{print}' input.txt

解释:

NR % 4 == 1 { # for every input line, which line number (NR) modulo 4 is 1
    print [=11=]; # print the line
}

如果你喜欢sed

sed -n '0~4p'

很有趣,这正是 man sed

中显示的示例

'FIRST~STEP' This GNU extension matches every STEPth line starting with line FIRST. In particular, lines will be selected when there exists a non-negative N such that the current line-number equals FIRST + (N * STEP). Thus, one would use '1~2' to select the odd-numbered lines and '0~2' for even-numbered lines; to pick every third line starting with the second, '2~3' would be used; to pick every fifth line starting with the tenth, use '10~5'; and '50~0' is just an obscure way of saying '50'.

 The following commands demonstrate the step address usage:

      $ seq 10 | sed -n '0~4p'
      4
      8

您似乎在尝试使用 Bash 语法,即使您的问题被标记为

即便如此,还是有很多错误。赋值运算符后不能有 space ,需要引用 sed 脚本(否则它认为 P 是第一个文件名......或者我猜你实际上意思是 p).

但是您需要循环文件 8000 次并在每次迭代中打印一行的想法也有缺陷。您可以告诉 sed 使用单个脚本打印每四行,例如

sed -n -e 1p -e 5p -e 9p ... filename

不过我会切换到 Awk。

awk 'FNR%4==1' filename