Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash read split file after string

Tags:

file

bash

split

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

like image 588
Sergio Peres Avatar asked Jul 02 '26 18:07

Sergio Peres


1 Answers

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
like image 80
Quasímodo Avatar answered Jul 05 '26 07:07

Quasímodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!