The sed (Stream Editor) command in Linux is a powerful tool used for text processing and file modification. It allows users to search, replace, insert, and delete text in files efficiently, making it a vital command for automation and scripting. In this guide, we will explore how to use the sed command to update files in Linux with practical examples.
The sed command is widely used for:
Text Replacement – Easily replace words, phrases, or patterns in files.
 Batch Processing – Modify multiple files at once using scripts.
 Efficiency – Processes large files quickly without opening them.
 Inline Editing – Modify files directly from the command line.
 Automation – Used in scripts to handle repetitive text modifications.
The general syntax of the sed command is:
sed [OPTIONS] 's/old-text/new-text/g' filenameWhere:
To replace a specific word in a file, use:
sed 's/Linux/Ubuntu/g' file.txtThis replaces the first occurrence of “Linux” with “Ubuntu” in each line of file.txt.
To replace all occurrences of a word globally in a file:
sed 's/Linux/Ubuntu/g' file.txtThe g flag ensures that every occurrence in a line is replaced.
To make changes directly in the file without displaying the output:
sed -i 's/Linux/Ubuntu/g' file.txtThe -i option enables in-place editing, meaning the original file is modified without needing to save a separate version.
To modify only specific lines in a file, specify the line number:
sed '3s/Linux/Ubuntu/' file.txtThis command replaces “Linux” with “Ubuntu” only on line 3.
To delete all lines containing a specific word, use:
sed '/unwanted-text/d' file.txtThis removes all lines that contain “unwanted-text”.
To remove a specific line, use:
sed '5d' file.txtThis deletes line 5 from file.txt.
To add a line before a specific line number:
sed '3i\This is a new line' file.txtThis inserts “This is a new line” before line 3.
To insert a line after a specific line number:
sed '3a\This is an appended line' file.txtThis appends “This is an appended line” after line 3.
To replace text in multiple files at once:
sed -i 's/Linux/Ubuntu/g' *.txtThis command modifies all .txt files in the directory, replacing “Linux” with “Ubuntu”.
To perform multiple modifications at once:
sed -i -e 's/Linux/Ubuntu/g' -e 's/Server/Cloud/g' file.txtThis replaces “Linux” with “Ubuntu” and “Server” with “Cloud” in file.txt.
To replace numbers in a file:
sed 's/[0-9]/#/g' file.txtThis replaces all digits with #.
To extract and display lines from 5 to 10:
sed -n '5,10p' file.txtThe -n option prevents printing the entire file, only showing lines 5-10.
The sed command is a versatile and efficient tool for updating files in Linux. Whether you need to replace text, delete lines, or insert content, sed can automate and simplify these tasks. By mastering sed, you can improve your workflow and enhance productivity in Linux administration and scripting.