Main menu

Pages

Mastering Text Manipulation with 'sed': Harnessing the Power of Stream Editing




The 'sed' command, short for stream editor, is a versatile and powerful utility in Linux for text manipulation. It operates on text files line by line, allowing you to perform a wide range of editing operations. In this comprehensive guide, we will delve into the 'sed' command and explore practical examples that showcase its capabilities. By mastering 'sed', you'll gain the skills to effortlessly manipulate text on the Linux platform. Let's dive in!

1. Replace Text: 

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

2. Replace Text in Place (Inline Editing):
sed -i 's/old-text/new-text/' filename.txt

3. Replace Only on Specific Line:
sed '3s/old-text/new-text/' filename.txt

4. Replace Globally (All Occurrences on Each Line):
sed 's/old-text/new-text/g' filename.txt

5. Delete Lines:
sed '3d' filename.txt

6. Delete Range of Lines:
sed '2,5d' filename.txt

7. Print Specific Line:
sed -n '5p' filename.txt

8. Print Range of Lines:
sed -n '2,5p' filename.txt

9. Print Lines Matching a Pattern:
sed -n '/pattern/p' filename.txt

10. Append Text After a Specific Line:
sed '/pattern/a\New line to append' filename.txt

11. Insert Text Before a Specific Line:
sed '/pattern/i\New line to insert' filename.txt

12. Append Text at the End of Each Line:
sed 's/$/ Appended Text/' filename.txt

13. Delete Blank Lines:
sed '/^$/d' filename.txt

14. Substitute Delimiter:
sed 's|old-text|new-text|' filename.txt

15. Transform Case (Upper to Lower):
sed 's/\<[A-Z]\+>/\L&/g' filename.txt

16. Transform Case (Lower to Upper):
sed 's/\<[a-z]\+>/\U&/g' filename.txt

17. Invert Matching Lines:
sed -n '/pattern/!p' filename.txt

18. Print Line Numbers:
sed '=' filename.txt | sed 'N;s/\n/ /'

19. Delete Leading Whitespace:
sed 's/^[ \t]*//' filename.txt

20. Reverse Order of Lines:

sed '1!G;h;$!d' filename.txt

Conclusion:

By mastering the 'sed' command, you unlock a world of possibilities for manipulating text in Linux. Whether it's replacing text, deleting lines, printing specific ranges, or performing pattern-based operations, 'sed' offers the versatility you need. Incorporate these examples into your workflow, and you'll become proficient in effortlessly manipulating text files on the Linux platform. Empower yourself with the power of 'sed' and take your text manipulation skills to new heights.

reactions