Print every n lines from a file

后端 未结 4 865
醉话见心
醉话见心 2021-01-21 05:10

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

For instance, I want to replace sed -n \'1~5p\'

相关标签:
4条回答
  • 2021-01-21 05:33

    The point is, you should use double quote " instead of the single one to wrap your sed codes. Variable won't be expanded within single quote. so:

    sed -n "1~${i} p"
    
    0 讨论(0)
  • 2021-01-21 05:37

    why a sed ?

    head -${i} YourFile
    
    0 讨论(0)
  • 2021-01-21 05:39

    awk can also do it in a more elegant way:

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

    With -v n=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 -v n=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
    
    0 讨论(0)
  • 2021-01-21 05:42

    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
    ffffdffffdffffdffffdffffdffffdffffffffd
    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.

    0 讨论(0)
提交回复
热议问题