我有一个文本文件:
Hello
1
2
3
(unknown number of lines)
Hello
(unknown number of lines)
Hello
(unknow number of lines)
Hello
如何在两个第一个“hello”之间剪切线并将其保存到文件中?
所以输出将是
1
2
3
(unknown number of lines)
使用 awk :
awk '$1=="Hello"{c++;next} c==1' oldfile | tee newfile
要第 N 次出现,请更改计数变量:
awk -v count=1 '$1=="Hello"{c++;next} c==count' oldfile | tee newfile
这是一个对我有用的简单 bash 脚本:
#!/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
像这样工作:
$./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
这就是我所拥有的:
$cat output.txt
1
2
3
(unknown number of lines)
并且 test.txt 包含:
Hello
1
2
3
(unknown number of lines)
Hello
(unknown number of lines)
Hello
(unknow number of lines)
Hello