Search code examples
unixsedcut

Cutting the top two lines after every six lines from a file containing 180 lines


I want to extract the top two lines from a file (a set of 180 lines) such that, if I group the file in to sets of 6-6 lines, I get the first two lines as my output. So I should be able to get the 1st,2nd followed by 7th,8th and so on. I tried using sed for this but not getting the desired output.

Could some one please suggest the logic to be implemented in here

My requirement is to make some modifications on the first two lines (like removing certain characters), for every set of 6 lines.

Example:

This is line command 1 for my configuration
This is line command 2 for my configuration
This is line command 3 for my configuration
This is line command 4 for my configuration
This is line command 5 for my configuration
This is line command 6 for my configuration

The output I want is:

This is line command 1
This is line command 2 
This is line command 3 for my configuration
This is line command 4 for my configuration
This is line command 5 for my configuration
This is line command 6 for my configuration

This has to repeat for every 6 commands out of 180 commands.


Solution

  • You can do it using the modulus of the division of the line number / 6. If it is 1 or 2, then print the line. Otherwise, do not.

    awk 'NR%6==1 || NR%6==2' file
    

    NR stands for number of record, which in this case is "number of line" because the default record is a line. || stands for "or". Finally, it is not needed to write any print, because it is the default behaviour of awk.

    Example:

    $ seq 60 | awk 'NR%6==1 || NR%6==2'
    1
    2
    7
    8
    13
    14
    19
    20
    25
    26
    31
    32
    37
    38
    43
    44
    49
    50
    55
    56
    

    Based on your update, this can make it:

    $ awk 'NR%6==1 || NR%6==2 {$6=$7=$8=$9} 1' file
    This is line command 1   
    This is line command 2   
    This is line command 3 for my configuration
    This is line command 4 for my configuration
    This is line command 5 for my configuration
    This is line command 6 for my configuration
    This is line command 7   
    This is line command 8   
    This is line command 9 for my configuration
    This is line command 10 for my configuration
    This is line command 11 for my configuration
    This is line command 12 for my configuration
    This is line command 13   
    This is line command 14   
    This is line command 15 for my configuration
    This is line command 16 for my configuration
    This is line command 17 for my configuration
    This is line command 18 for my configuration
    This is line command 19   
    This is line command 20   
    This is line command 21 for my configuration
    This is line command 22 for my configuration
    This is line command 23 for my configuration
    This is line command 24 for my configuration