2

Can you help me to split a file that looks like the following into two files depending on the second column (groups starting with value 1 plus the following 2 lines should be in one file and groups starting with value 0.1 plus the following 2 lines should be in the second file):

A 1
A 10
A 100
B 0.1
B 1
B 10
C 1
C 10
C 100
D 0.1
D 1
D 10

Expected output file 1:

A 1
A 10
A 100
C 1
C 10
C 100

Expected output file 2:

B 0.1
B 1
B 10
D 0.1
D 1
D 10

Kind regards!!

1
  • 1
    Welcome to the site. Please edit your post to indicate what you already tried and where you faced problems. That way you can avoid receiving answers you already know won't work.
    – AdminBee
    Nov 23, 2021 at 11:33

3 Answers 3

3
$ cat tst.awk
!(c&&c--) {
    out = "out" ($2 == 1 ? 1 : 2)
    c = 2
}
{ print > out }

$ awk -f tst.awk file

$ head out?
==> out1 <==
A 1
A 10
A 100
C 1
C 10
C 100

==> out2 <==
B 0.1
B 1
B 10
D 0.1
D 1
D 10

See printing-with-sed-or-awk-a-line-following-a-matching-pattern for what c&&c-- does and other similar awk idioms.

2

The following awk program will work:

awk '$2=="1"&&!(n+m){n=1}
     $2=="0.1"&&!(n+m){m=1}
     n&&n<4{print > "file1.txt"; if (++n==4) n=0}
     m&&m<4{print > "file2.txt"; if (++m==4) m=0}' input.txt

This will inspect the second column and check if its value is 1 or 0.1.

  • If it is 1 and we are not yet in a "line group", it sets a counter n to 1. If that counter is non-zero, but smaller than 4, the current line will be printed to file1.txt (amounting to the starting line and the two following lines). If the specified number of lines is reached, the counter is reset to 0, indicating that the line group is finished.
  • The same is true for lines where the second field is 0.1, only the counter is called m and the output file file2.txt.
  • A group start is only checked if we are not already inside a group, i.e. both m and n are zero.
0
1

Using sed:

sed -n \
    -e '/[[:blank:]]1$/    {' -e 'N;N; w file1' -e '}' \
    -e '/[[:blank:]]0\.1$/ {' -e 'N;N; w file2' -e '}' file

The above writes the current line and the next two lines to the file called file1, if the current line ends with a blank (space or tab) followed by 1.

The code writes the current line and the next two lines to the file called file2, if the current line ends with a blank followed by 0.1.

The N command in sed appends the next line of input to the editing buffer, and w writes the current contents of the buffer to a named file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.