如何从文件bash unix中删除几行

时间:2013-03-27 23:13:54

标签: bash sed awk cut

我有一个文本文件:
你好
1
2
3
(未知行数)
你好
(未知行数)
你好
(未知行数)
你好

如何在两个第一个“hello”之间剪切线并将其保存到文件中? 所以输出将是

1
2
3
(未知行数)

2 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:0)

这是一个适合我的简单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