doom4
doom4

Reputation: 695

Split file after number occurrence of delimiter

my question is essentially the same as answered in split file on Nth occurrence of delimiter except that the solution will strip the delimiter before splitting. How would I split a fail after Nth occurrence of a delimiter while keeping all characters of the initial file? Example file:

aaa
bbb
$$$$
ccc
ddd
eee
$$$$
fff
ggg
hhhhh
$$$$

split after every 2nd occurrence of $$$$

awk '/^\$\$\$\$$/ { if(++delim % 2 == 0) { next } } { file = sprintf("chunk%s.txt", int(delim / 2)); print; END { print "ds" } }' < file

would delete the delimiter at the end of the chunk file

Upvotes: 1

Views: 216

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133428

If I get it correctly and you want to split files on every 2nd occurrence of $$$$ then try following.

awk -v file="1" -v occur="2" '
{
  print > (file".txt")
}
/^\$\$\$\$$/{
  count++
  if(count%occur==0){
    if(file){
      close(file".txt")
      ++file
    }
  }
}
'  Input_file

Upvotes: 2

Related Questions