Notes & TILs
Search…
Line Editors in Linux, Tips and Tricks
I will log various ways through which tools like sed, cut and tr can be used.

sed πŸ˜₯

  • Print specific lines from a file using line numbers.
    1
    # print lines 12 to 22
    2
    sed -n '12,22p' file.txt
    Copied!
  • Omit first line of output.
    1
    sed -n '1!p'
    Copied!
  • Omit last line of file.
    1
    sed '$d' file.txt
    Copied!
  • Print everything after a pattern (inclusive).
    1
    sed -n '/pattern/,$ p' file.txt
    Copied!
  • Print everything before a pattern (inclusive).
    1
    sed -n '1,/pattern/ p' file.txt
    Copied!
  • Print everything between two patterns
    1
    sed -nE '/^foo/,/^bar/p' file.txt
    Copied!
  • Avoid printing the searched pattern
    1
    sed -n 's/^my_string//p' file.md
    Copied!
  • Insert contents of file after a certain line
    1
    sed '5 r newfile.txt' file.txt
    Copied!
  • Change line containing regex/pattern match
    1
    sed '/MATCH THIS/c\REPLACE WITH THIS' file.txt
    Copied!

tr ➑️

  • Translate (or convert) all () to [] in a text file.
    1
    tr '()' '[]'
    Copied!
  • Translate all occurrences of multiple spaces with a single space.
    1
    tr -s ' '
    Copied!
  • Remove unwanted characters from string.
    1
    # will delete % and ;
    2
    echo "1;00%" | tr -d "%;"
    Copied!

cut βœ‚οΈ

  • Print every 4th word (or field) from a space separated STDIN.
    1
    cut -d' ' -f4
    Copied!
    I don't know about you but this is pretty cool.

awk

  • Don't print first line of file
    1
    awk NR\>1 file.txt
    Copied!

Resources & Learning Material

Last modified 1mo ago