Sed Command and Its Different Usages
sed (Stream Editor) is a powerful command-line tool used for text processing, including search, replace, insert, and delete operations.
Basic Syntax
sed [OPTIONS] 's/SEARCH_PATTERN/REPLACEMENT/FLAGS' FILE
Common Flags
-i→ Edit files in-place (modify original file)g→ Replace all occurrences in a line (default: only first occurrence)p→ Print modified linesd→ Delete lines-n→ Suppress automatic printing
Usage Examples
1. Replace Text in a File
Replace first occurrence of 'foo' with 'bar' in a file
sed 's/foo/bar/' file.txt
Replace all occurrences of 'foo' with 'bar' in a file
sed 's/foo/bar/g' file.txt
Replace and save changes to the same file
sed -i 's/foo/bar/g' file.txt
2. Replace Text in Multiple Files
sed -i 's/foo/bar/g' *.txt
3. Delete Lines
Delete lines containing 'error'
sed '/error/d' file.txt
Delete empty lines
sed '/^$/d' file.txt
4. Extract Specific Lines
Print lines 5 to 10
sed -n '5,10p' file.txt
5. Update Dates in a File
Update all occurrences of 2021.MM.DD to the current date in a CSV file
sed -i "s/2021\.[0-9]\{2\}\.[0-9]\{2\}/$(date +%Y.%m.%d)/g" file.csv
Update dates in all CSV files in a directory
sed -i "s/2021\.[0-9]\{2\}\.[0-9]\{2\}/$(date +%Y.%m.%d)/g" *.csv
Conclusion
sed is a versatile tool that simplifies text manipulation in Linux. It is widely used for scripting and automation in text processing tasks.
💡 Tip: Always test sed commands without -i before modifying files permanently!
Written by A.M. Rinas