Search code examples
linuxbashperlsed

Linux - Delete all lines from a given line number


I am trying to delete a file's contents from a supplied line number using sed. The problem is that sed isn't accepting the variable I supply to it

line_num=$(grep -n "debited" file.csv | sed -n '2 s/:.*//p') && sed -i.bak "$line_num,$d" file.csv

The idea is to delete all lines from a file after & including the second occurence of the pattern.

I'm not stubborn with sed. Awk & perl could do too.


Solution

  • I always suggest ed for editing files over trying to use sed to do it; a program intended from the beginning to work with a file instead of a stream of lines just works better for most tasks.

    The idea is to delete all lines from a file after & including the second occurence[sic] of the pattern

    Example:

    $ cat demo.txt
    a
    b
    c
    debited 12
    d
    e
    debited 14
    f
    g
    h
    $ printf "%s\n" '/debited/;//,$d' w | ed -s demo.txt
    $ cat demo.txt
    a
    b
    c
    debited 12
    d
    e
    

    The ed command /pattern/;//,$d first sets the current line cursor to the first one that matches the basic regular expression pattern, then moves it to the next match of the pattern and deletes everything from there to the end of the file. Then w writes the changed file back to disk.