How can I split a text file based on the first match of a pattern? The file only needs to be split in 2 parts, one containing everything prior to the line matching the pattern, one containing the line matching, and everything after. The lines after it will also contain the pattern again, but that shouldn't trigger multiple parts.
3 Answers
Try:
sed '/pattern/q' file.txt | grep -v "pattern" > part1.txt
sed -n `sed -n '/pattern/=' file.txt | head -1`',$p' file.txt > part2.txt
Where file.txt
- your file
I'm not sure I've understood the last sentence however:
This should copy all the line of your file till the line of the pattern excluded
head -n `grep -e "YOUR PATTERN" -n YOURFILE | head -1 | awk -F ":" '{print $1-1}'` YOURFILE > FIRST_FILE_OUTPUT.txt
this sould copy from the line of pattern included to the end.
tail -n `grep -e "YOUR PATTERN" -n YOURFILE | head -1 | awk -F ":" '{print "+"$1}'` YOURFILE > SECOND_FILE_OUTPUT.txt
where YOURFILE us the input file to split YOUR PATTERN is the "key" you want to search in your file. FIRST_FILE_OUTPUT.txt and SECOND_FILE_OUTPUT.txt are the output file in which you'll find the first and the second part of your file.
How about
awk -F'+' '{ print $1 }' < abc > firstpart.txt
awk -F'+' '{ print $1 }' < abc > secondpart.txt
-
1