I find a old C plus plus project wrote all log to a local file, it didn’t truncate the local file but just append strings.
Here is a simple file, I used the string “finished” to split it to different parts.
this is a story about history
haha
finished
the new contents
hello word.
finished
this is the third file
do you know
Find the line numbers of the string in the file.
λ cat -n txt|grep 'finished'|awk '{print $1}'
3
6
As we know sed
can output n-m lines on the file.
λ sed -n 1,3p txt
this is a story about history
haha
finished
So lets combine the main logics to make our shell script work.
The script:
λ cat split.sh
numbers=`cat -n txt|grep 'finished'|awk '{print $1}'`
#echo $numbers
firstNumber=1
fileCount=1
fileAllCount=`wc -l txt|awk '{print $1}'`
for secondNumner in $numbers; do
sed -n ${firstNumber},`expr ${secondNumner} - 1`p txt > $fileCount.txt
fileCount=`expr $fileCount + 1`
firstNumber=`expr $secondNumner + 1`
done
sed -n ${firstNumber},${fileAllCount}p txt > $fileCount.txt
The generated files: