2

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 3

2

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

1
  • This is the best answer and saved me a bunch of time - thank you!
    – dossy
    Mar 9, 2020 at 17:25
0

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.

-1

How about

awk -F'+' '{ print $1 }' < abc > firstpart.txt
awk -F'+' '{ print $1 }' < abc > secondpart.txt
1
  • 1
    That's the exact same command twice? This doesn't do anything.
    – Eugene K
    May 18, 2019 at 14:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .