Linux – sed Command

The sed command stands for “stream editor.” It is used to perform basic text transformations on an input stream. The sed command is commonly used for text substitution, filtering, and other text processing tasks.



Tutorials dojo strip

Initial Example

Using sed to replace the first occurrence of the word “old” with “new” in a file called file.txt:

sed 's/old/new/' file.txt




SED Command

ParameterDescription
-n, --quiet, --silentSuppress automatic output printing, only print lines explicitly specified
--debugOutput detailed execution steps for debugging purposes
-e script, --expression=scriptAdd the provided script to the list of commands to be executed
-f script-file, --file=script-fileExecute commands from the specified script file
--follow-symlinksFollow symbolic links when making in-place edits
-i[SUFFIX], --in-place[=SUFFIX]Edit files directly, optionally making a backup with the given suffix
-l N, --line-length=NSet the maximum line length for the l command, wrapping lines as needed
--posixDisable all GNU-specific extensions
-E, -r, --regexp-extendedUse extended regular expressions for pattern matching (POSIX -E for portability)
-s, --separateTreat each file as a separate input stream, rather than a single continuous stream
--sandboxRun in sandbox mode, disabling the e, r, and w commands for security
-u, --unbufferedMinimize input buffering and flush output buffers more frequently
-z, --null-dataUse NUL characters to separate lines of input instead of newline characters
--helpShow help information and exit
--versionDisplay version information and exit




Examples

1. Basic Text Substitution

To replace the first occurrence of “old” with “new” in each line of a file:

sed 's/old/new/' filename.txt

2. Global Text Substitution

To replace all occurrences of “old” with “new” in each line of a file:

sed 's/old/new/g' filename.txt

3. In-Place Editing

To perform text substitution directly in the file (without creating a new file):

sed -i 's/old/new/g' filename.txt

4. Deleting Lines

To delete lines that match a specific pattern:

sed '/pattern/d' filename.txt

5. Printing Specific Lines

To print only the lines that match a specific pattern:

sed -n '/pattern/p' filename.txt

6. Replace on a Specific Line

To replace text on a specific line number (e.g., line 3):

sed '3s/old/new/' filename.txt

7. Using Regular Expressions

To use regular expressions for more complex text manipulation:

sed 's/[0-9]/#/g' filename.txt

8. Append Text After a Match

To append text after lines that match a specific pattern:

sed '/pattern/a\new text' filename.txt

9. Insert Text Before a Match

To insert text before lines that match a specific pattern:

sed '/pattern/i\new text' filename.txt




Linux Playground

Scroll to Top