Sed - Stream EDitor

Contents

    sources

    -i update source file

    Pattern building

    Pattern substitution

    Basic substitutions

    Note: several options can be combined, ie sed "s/foo/bar/gi"

    trim

    Advanced substitutions

    Print or delete full line

    p = print

    d = delete

    q = quit

    Insert or append a line

    i text = Insert line (before)

    a text = Append line (after)

    Using a pattern file

    ... | sed -f filename.txt

    cat filename.txt
    s/un/one/
    s/deux/two/
    

    Playing with pattern space and hold space

    sed -n "/password/{x;p};h" print the line before a line containing 'password'

    sed -n "/^$/{p;h;};/./{x;/./p;}" delete the last line of each paragraph
    → so intuitive in order to achieve this result ☺

    TODO: to be updated

    # delete duplicate lines from a sorted file (emulates "uniq"). First
    # line in a set of duplicate lines is kept, the rest are deleted
    sed '$!N; /^\(.*\)\n\1$/!P; D'

    # delete all CONSECUTIVE blank lines from file except the first; also
    # deletes all blank lines from top and end of file (emulates "cat -s")
    sed '/./,/^$/!d' # method 1, allows 0 blanks at top, 1 at EOF
    sed '/^$/N;/\n$/D' # method 2, allows 1 blank at top, 0 at EOF

    # delete all CONSECUTIVE blank lines from file except the first 2:
    sed '/^$/N;/\n$/N;//D'

    # delete all trailing blank lines at end of file
    sed -e :a -e '/^\n*$/N;/\n$/ba'

    Sed multiline (ou équivalent avec perl)

    cat a
    one
    two
    three
    four
    five
    six
    eg244698 ~ $ cat a | perl -0pe 's/two\nthree/yo/'
    one
    yo
    four
    five
    six
    eg244698 ~ $ cat a
    one
    two
    three
    four
    five
    six
    eg244698 ~ $ perl -i -0pe 's/two\nthree/yo/' a
    eg244698 ~ $ cat a
    one
    yo
    four
    five
    six
    

    Color

    alias colorlog="sed 's#FATAL#\x1b[1;41m&\x1b[0m#;s#ERROR#\x1b[1;31m&\x1b[0m#;s#WARN#\x1b[1;33m&\x1b[0m#;s#INFO#\x1b[1;34m&\x1b[0m#;s#DEBUG#\x1b[1;36m&\x1b[0m#;s#TRACE#\x1b[1;32m&\x1b[0m#'"

    Proudly Powered by Zim 0.75.2.

    Template by Etienne Gandrille, based on ZeroFiveEight and using JQuery Toc Plugin.