Reputation: 33
i have a file that contains random lines and key words END:
line 1
line 2
...
line 23
END
line 25
....
line 40
END
and i want to split it into multiple files based on the key word END and have it inside each file as: file 1
line 1
line 2
...
line 23
END
file 2
line 25
.....
line 40
END
I tried:
csplit -k file_name '/END/' '{*}' but i do not get the correct output.
Upvotes: 1
Views: 460
Reputation: 67517
with awk
$ awk '{f= FILENAME"."(c+1); print > f} /^END$/{close(f); c++}' file
$ head file.*
==> file.1 <==
line 1
line 2
...
line 23
END
==> file.2 <==
line 25
....
line 40
END
Edge case behavior:
if the input file is empty (no lines), no output will be generated.
if the file has blank line(s), exact copy of the file is generated as a partition (same as with no END
marker or only one at the end).
Upvotes: 2
Reputation: 4698
Add an offset of 1 to the regex to include the matching END
in the current file. I also added to ^
and $
to anchor the regex.
csplit -k file -f file --elide-empty-files '/^END$/1' '{*}'
-f file
Sets the output filename prefix--elide-empty-files
This is a GNU extension and doesn't output empty files (in this case an empty file file02
)Output:
$ head file0*
==> file00 <==
line 1
line 2
...
line 23
END
==> file01 <==
line 25
....
line 40
END
Upvotes: 3