我有一个包含几行的文件:
C 1.31729690416596 -0.05166770188922 0.05026556004853
C 2.15676687192808 -0.87605403673920 0.93010807487406
C 1.45516592682388 -0.49804136618225 -1.24011085742027
C 2.67489108786199 -2.06116694592319 0.09667460087481
C 2.24626744432148 -1.81826783081380 -1.24626795859707
C 0.12278380551129 -0.78127661791244 -1.79035714840462
C 0.11627012096698 -2.05095769577445 -2.31049614254010
C 1.41908665901196 -2.77247309785857 -1.91624359298119
我需要在一次操作中打印一系列复杂的行,例如第 1 行和第 4 到 7 行,这是 1,4-7。如何获取这些行而不是逐行搜索。
答案1
ed行编辑器:
printf '%s\n' '1p' {4..7}p 'Q' | ed -s - file
awk:
printf 'NR==%d\n' 1 {4..7} | awk -f - file
sed流编辑器:
printf '%sp\n' 1 4,7 | sed -nf - file
perl:
perl -lne 'print if grep { $_ == $. } (1, 4..7)' file
答案2
使用awk
var NR
:
awk 'NR == 1 || NR >= 4 && NR <= 7' file
C 1.31729690416596 -0.05166770188922 0.05026556004853
C 2.67489108786199 -2.06116694592319 0.09667460087481
C 2.24626744432148 -1.81826783081380 -1.24626795859707
C 0.12278380551129 -0.78127661791244 -1.79035714840462
C 0.11627012096698 -2.05095769577445 -2.31049614254010
答案3
命令
sed -n -e '1p' -e '4,7p' filename
输出
C 1.31729690416596 -0.05166770188922 0.05026556004853
C 2.67489108786199 -2.06116694592319 0.09667460087481
C 2.24626744432148 -1.81826783081380 -1.24626795859707
C 0.12278380551129 -0.78127661791244 -1.79035714840462
C 0.11627012096698 -2.05095769577445 -2.31049614254010