简体   繁体   中英

Print every n lines from a file

I'm trying to print every n th line from file, but n is not a constant but a variable.

For instance, I want to replace sed -n '1~5p' with something like sed -n '1~${i}p' .

Is this possible?

awk can also do it in a more elegant way:

awk -v n=YOUR_NUM 'NR%n==1' file

With -vn=YOUR_NUM you indicate the number. Then, NR%n==1 evaluates to true just when the line number is on a form of 7n+1 , so it prints the line.

Note how good it is to use awk for this: if you want the lines on the form of 7n+k , you just need to do: awk -vn=7 'NR%n==k' file .

Example

Let's print every 7 lines:

$ seq 50 | awk -v n=7 'NR%n==1'
1
8
15
22
29
36
43
50

Or in sed :

$ n=7
$ seq 50 | sed -n "1~$n p" # quote the expression, so that "$n" is expanded
1
8
15
22
29
36
43
50

关键是,您应该使用双引号"而不是单引号来包装sed代码。变量不会在单引号内扩展。因此:

sed -n "1~${i} p"

You can do it like this for example:

i=3
sed "2,${i}s/.*/changed line/g" InputFile

Example:

AMD$ cat File
aaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccc
ddddddddddddddddddddddd
eeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffff
ggggggggggggggggggggg

AMD$ i=4; sed "2,${i}s/.*/changed line/g" File
aaaaaaaaaaaaaaaaaaaaaaaa
changed line
changed line
changed line
eeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffff
ggggggggggggggggggggg

The key is to use " " for variable substitution.

为什么要sed?

head -${i} YourFile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM