api: YAML JSON TOON Database version: 1.0.0 format: toon dataset: id: 2478 slug: sed-reference title: Sed Reference description: "Common sed commands, substitutions, and flags." summary: "sed stream-editor patterns: substitution, in-place edits, deleting and printing lines, inserting and appending, regex groups, multiple commands and address ranges, extended with line deletion by pattern, nth-occurrence replacement, case-insensitive matching, trailing-whitespace removal and alternate delimiters." use_when[2]: You need a one-line text substitution or line filter.,You need the idiom for a common sed task. caveats[2]: sed -i behaves differently on GNU and BSD/macOS (macOS needs -i '' ); use a suffix such as -i.bak for portability and safety.,The I flag for case-insensitive matching is a GNU extension. related[4]: awk-reference,unix-text-processing-commands,file-operations,shell-scripting-guide entry_count: 16 fields[3]{section,field,type,example}: data,pattern,string,Substitute data,command,string,sed 's/foo/bar/g' file data,description,string,Replace all occurrences of foo with bar globall… category: Unix Commands category_slug: unix-commands tags: "unix,sed,text-processing,stream-editor" view_count: 21 created_at: 1792832553 updated_at: 1792832553 data[16]{pattern,command,description}: Substitute,sed 's/foo/bar/g' file,Replace all occurrences of foo with bar globally. In-place edit,sed -i 's/foo/bar/g' file,Edit file in place; use -i.bak for backup. Delete lines,sed '3d' file,Delete line 3. Use /pattern/d for pattern match. Print lines,"sed -n '5,10p' file",Print lines 5 through 10 only. Insert/append,"sed '3i\\nNew line' file",Insert text before line 3. Regex group,"sed 's/(\\d+)/[\\1]/g'",Capture digits in parentheses and wrap in brackets. Multiple commands,sed -e 's/a/A/g' -e 's/e/E/g',Apply multiple substitution commands. Address range,"sed '1,5s/old/new/' file",Substitute only in lines 1 through 5. Delete blank lines,sed '/^$/d' file,Remove all empty lines. Print a specific line,sed -n '5p' file,Print only line 5; -n suppresses default output. Print the last line,sed -n '$p' file,The $ address means the last line. Replace the Nth occurrence,sed 's/foo/bar/2' file,Replace only the second occurrence on each line. Case-insensitive substitute,sed 's/foo/bar/Ig' file,"GNU sed: the I flag ignores case." Substitute within matching lines,sed '/error/s/foo/bar/g' file,Apply the substitution only on lines containing 'error'. Strip trailing whitespace,"sed 's/[ \\t]*$//' file",Remove spaces and tabs at the end of each line. Use another delimiter,sed 's|/usr/local|/opt|g' file,Choose a delimiter other than / when the pattern contains slashes.