Sergio Peres
Sergio Peres

Reputation: 55

bash read split file after string

I am tring to create one shell script to split text files after one specific STRING.

Line of text 
Line of text 
STRING
Line of text 
Line of text 

I pretend to have 2 files, one from begining to STRING and other with STRING to end contents.

Thanks for any help

Upvotes: 3

Views: 639

Answers (1)

Quasímodo
Quasímodo

Reputation: 4004

With sed:

sed -n '1,/STRING/p' inputfile > file1
sed -n '/STRING/,$p' inputfile > file2

With awk:

awk '/STRING/{flag=1;print>"file1"}
    flag {print>"file2";next}
    {print>"file1"}
' inputfile

If you need the line to contain the exact word STRING and nothing more, then just substitute STRING for ^STRING$ in the scripts above.


If you don't want STRING to be present in first file,

awk '/STRING/{flag=1}
    flag {print>"file2";next}
    {print>"file1"}
' inputfile

Upvotes: 4

Related Questions