Sed in Linux

  1. Introduction



  2. Basic Syntax
  3. sed 'command' filename
    


  4. Print File Contents (Default Behavior)
  5. sed '' file.txt
    


  6. Substitution Command (s)
  7. sed 's/old/new/' file.txt
    


  8. Global Replacement (g)
  9. sed 's/foo/bar/g' file.txt
    


  10. Using Different Delimiters
  11. sed 's|/usr/local|/opt/apps|' file.txt
    


  12. Edit File In-Place (-i)
  13. sed -i 's/foo/bar/g' file.txt
    
    sed -i.bak 's/foo/bar/g' file.txt
    


  14. Print Specific Lines
  15. sed -n '3p' file.txt
    
    sed -n '5,8p' file.txt   # print lines 5 to 8
    


  16. Delete Lines
  17. sed '3d' file.txt
    
    sed '2,5d' file.txt      # delete lines 2 to 5
    


  18. Insert and Append Lines
  19. sed '3i This is an inserted line' file.txt
    
    sed '3a This is an appended line' file.txt
    


  20. Replace a Whole Line
  21. sed '4c This replaces line 4 completely' file.txt
    


  22. Using Patterns Instead of Line Numbers
  23. sed '/error/d' file.log
    
    sed '/BEGIN/,/END/p' config.txt
    


  24. Multiple Commands
  25. sed -e 's/foo/bar/' -e 's/x/y/' file.txt
    
    sed '
        s/foo/bar/g
        s/apple/orange/g
    ' file.txt
    


  26. Advanced Example: Remove Empty Lines
  27. sed '/^$/d' file.txt
    


  28. Advanced Example: Remove Trailing Spaces
  29. sed 's/[ ]*$//' file.txt
    


  30. Advanced Example: Replace Only on Matching Lines
  31. sed '/error/ s/failed/FAILED/' file.txt
    


  32. Hold Space and Pattern Space (For Advanced Users)

  33. sed 'h; $!d; x' file.txt
    


  34. Summary of Common sed Commands

  35. Command Description Example
    s/a/b/ Substitute first occurrence s/foo/bar/
    s/a/b/g Substitute all occurrences s/old/new/g
    p Print -n '3p'
    d Delete '/error/d'
    i Insert before '3i text'
    a Append after '3a text'
    c Replace line '4c new text'
    -i Edit file in-place -i 's/a/b/' file