Reputation: 1022
I have a text file:
Hello
1
2
3
(unknown number of lines)
Hello
(unknown number of lines)
Hello
(unknow number of lines)
Hello
How to cut lines between two first "hello" and save it to a file?
So the output will be
1
2
3
(unknown number of lines)
Upvotes: 2
Views: 5706
Reputation: 1341
Here's a simple bash script that worked for me:
#!/bin/bash
WORD="$1" # Word we look for, in this case 'Hello'
COUNT=0 # Internal counter for words
let MAXCOUNT="$2" # How many words to encounter before we stop
OUTPUT="$3" # Output filename
FILENAME="$4" # The file to read from
while read -r; do # read the file line by line
[ "$MAXCOUNT" -le "$COUNT" ] && break; # if we reached the max number of occurances, stop
if [[ "$WORD" = "$REPLY" ]]; then # current line holds our word
let COUNT=$COUNT+1; # increment counter
continue; # continue reading
else # if current line is not holding our word
echo "$REPLY" >> "$OUTPUT"; # print to output file
fi
done <"$FILENAME" # this feeds the while with our file's contents
Worked like this:
$./test.sh "Hello" 2 output.txt test.txt # Read test.txt, look for "Hello" and print all lines between the first two occurances into output.txt
This is what I've got:
$cat output.txt
1
2
3
(unknown number of lines)
And test.txt contains:
Hello
1
2
3
(unknown number of lines)
Hello
(unknown number of lines)
Hello
(unknow number of lines)
Hello
Upvotes: 0
Reputation: 185025
Using awk :
awk '$1=="Hello"{c++;next} c==1' oldfile | tee newfile
To have the Nth occurence, change the count variable :
awk -v count=1 '$1=="Hello"{c++;next} c==count' oldfile | tee newfile
Upvotes: 3