【问题标题】:how to cut several lines from file bash unix如何从文件bash unix中剪切几行
【发布时间】:2013-03-18 06:31:23
【问题描述】:

我有一个文本文件:

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)

【问题讨论】:

    标签: bash sed awk cut


    【解决方案1】:

    这是一个对我有用的简单 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
    

    【讨论】:

    • 如果$WORD=$PS1怎么办?
    【解决方案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
    

    【讨论】:

    • 哦,谢谢 =) 如果要在最后两个之间剪断你好?
    • 应该是 awk '$1=="Hello"{c++;next} c>2' oldfile > newfile?
    • 我有问题。而不是你好,我有一个#PS1 变量,所以它就像 [user@hostname pwd]# 并且上面的代码不起作用
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多