如何从bash unix文件中剪切几行

如何从bash unix文件中剪切几行,bash,sed,awk,cut,Bash,Sed,Awk,Cut,我有一个文本文件: 你好 1. 2. 3. (未知行数) 你好 (未知行数) 你好 (未知行数) 你好 如何在前两个“hello”之间剪切行并将其保存到文件中? 因此,输出将是 1 2. 3. (未知行数) 使用awk: awk '$1=="Hello"{c++;next} c==1' oldfile | tee newfile 要发生第n次,请更改count变量: awk -v count=1 '$1=="Hello"{c++;next} c==count' oldfile | tee n

我有一个文本文件:

你好 1. 2. 3. (未知行数) 你好 (未知行数) 你好 (未知行数) 你好 如何在前两个“hello”之间剪切行并将其保存到文件中?
因此,输出将是

1
2.
3.
(未知行数)
使用awk:

awk '$1=="Hello"{c++;next} c==1' oldfile | tee newfile
要发生第n次,请更改count变量:

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
这就是我得到的:

$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

哦,谢谢=)如果要在最后两个Hello之间划行呢?应该是awk'$1==“Hello”{c++;next}c>2'oldfile>newfile吗?我有个问题。我用了一个#PS1变量来代替Hello,所以它是smth[user@hostnamepwd]#上面的代码不起作用,如果$WORD=$PS1怎么办?
Hello
1
2
3
(unknown number of lines)
Hello
(unknown number of lines)
Hello
(unknow number of lines)
Hello