shell - Linux script: how to split a text into different files with match pattern -


for example: have text following:

jul 11 xxxx  xxxx start xxxxx .... .... .... jul 11 xxxx  xxxx stop xxxxx jul 11 xxxx  xxxx start xxxxx .... .... .... jul 11 xxxx  xxxx stop xxxxx .... 

now want split above text file different files based on "start" , "stop", like

/***text1.txt******/ jul 11 xxxx  xxxx start xxxxx .... .... .... jul 11 xxxx  xxxx stop xxxxx  /***text2.txt******/ jul 11 xxxx  xxxx start xxxxx .... .... .... jul 11 xxxx  xxxx stop xxxxx 

how can that? thanks.

this can make it:

$ awk '{if ($0 ~ /start/) a++} {print >> "file"a}' file 

explanation

  • {if ($0 ~ /start/) a++} looks lines containing word start. if so, increments variable a, 0 default.
  • {print >> "file"}' prints $0 (that is, whole line) file called "file" in same directory.
  • {print >> "file"a} prints line file called "file" + variable a, happens 0, 1, 2... prints file1, file2...

test

$ cat jul 11 xxxx  xxxx start xxxxx .... .... .... jul 11 xxxx  xxxx stop xxxxx jul 11 xxxx  xxxx start xxxxx here begins 2nd file .... .... .... jul 11 xxxx  xxxx stop xxxxx $ awk '{if ($0 ~ /start/) {a++}} {print >> "file"a}' $ cat file1 jul 11 xxxx  xxxx start xxxxx .... .... .... jul 11 xxxx  xxxx stop xxxxx $ cat file2 jul 11 xxxx  xxxx start xxxxx here begins 2nd file .... .... .... jul 11 xxxx  xxxx stop xxxxx 

Comments