How can I delete all lines before a specific string from a number of files

后端 未结 4 1869
醉话见心
醉话见心 2021-02-19 01:15

I have n files, like:

file1:

1aaa
2eee

Test        XXX
Hanna
Lars 

file2:

1fff
2ffffd
3zzz

Test        XXX
Mike
Charly         


        
相关标签:
4条回答
  • 2021-02-19 01:40

    This will work for your examples and even if the matched pattern is on the very first line:

    sed -n -E -e '/Text XXX/,$ p' input.txt | sed '1 d'
    

    For example if you input is simply

    Test        XXX
    Mike
    Charly
    

    This will give you

    Mike
    Charly
    

    If you want to keep the first match Test XXX then just use:

    sed -n -E -e '/Text XXX/,$ p' input.txt
    
    0 讨论(0)
  • 2021-02-19 01:40
    cat <<-EOF > file1.txt
    1aaa
    2eee
    
    Test        XXX
    Hanna
    Lars
    EOF
    
    cat file1.txt | sed -e '/Test *XXX/p' -e '0,/Test *XXX/d'
    

    Output:

    Test        XXX
    Hanna
    Lars
    

    Explanation:

    • -e '/Test *XXX/p' duplicates the line matching /Test *XXX/
    • -e '0,/Test *XXX/d' deletes from line 0 to the first line matching /Test *XXX/

    By duplicating the line, then removing the first one, we effectively retain the matched line, successfully deleting all lines BEFORE Test XXX

    Note: this will not work as expected if there are multiple Test XXX lines.

    0 讨论(0)
  • 2021-02-19 01:49

    You can do it with bash ( eg for 1 file)

    t=0
    while read -r line
    do
        [[ $line =~ Test.*XXX ]] && t="1"
        case "$t" in
         1) echo "$line";;
        esac
    done < file > tempo && mv tempo file
    

    Use a for loop as necessary to go through all the files

    0 讨论(0)
  • 2021-02-19 01:54

    This should work for you:

    sed -i '1,/Test XXX/d' file1
    sed -i '1,/Test XXX/d' file2
    

    or simply

    sed -i '1,/Test XXX/d' file*
    
    0 讨论(0)
提交回复
热议问题