I have the following sed commands to split a file in two:
sed -n '1,/(-!-)/{/(-!-)/!p}' file.temp file1.txt
sed -n '/(-!-)/,${/(-!-)/!p}' file.temp file2.txt
the file is like 123 (-!-) 321
and I got this result:
file1:
123
file2:
321
this works just great but I wanted it split to 4 files, it means I will use 3 separators
Can someone give me a hint about how to do it?
sedis probably not the right tool for this job.awk, on the other hand, is able to split records on arbitrary regular expressions, which ends up making this very easy. First, here’s a way to extract a particular section from your file.Given this input:
We can extract just section three like this:
Which gives us:
In this command, we’re setting awk’s record separator (the
RSvariable) to a regular expression matching the separator in your file. Normally,awkuses a newline as the record separator, so each line is a new record. By settingRSexplicitly to this regular expression, we are makingawktreat each section as a single entity.You can extract each section into a separate file like this:
This will give you the files
file1,file2, andfile3as output, each containing the content of the appropriate section. The filenames are generated from the value of the “prefix” variable (set by the-vprefix="file"option ) and the current record number.