sed Command in Linux/Unix - Examples and Output
Original File Content
Line one: Hello World
Line two: Welcome to Linux
Line three: sed is powerful
Line four: Learn Linux
Line five: Goodbye
1. Replace first 'Linux' with 'Unix' in each line
Command:
sed 's/Linux/Unix/' [Link]
Output:
Line one: Hello World
Line two: Welcome to Unix
Line three: sed is powerful
Line four: Learn Unix
Line five: Goodbye
2. Replace all 'Linux' with 'Unix' in each line
Command:
sed 's/Linux/Unix/g' [Link]
Output is same as above if each line has only one 'Linux'.
3. Print only line 2
Command:
sed -n '2p' [Link]
Output:
Line two: Welcome to Linux
4. Delete line 3
Command:
sed '3d' [Link]
Output:
Line one: Hello World
Line two: Welcome to Linux
Line four: Learn Linux
Line five: Goodbye
sed Command in Linux/Unix - Examples and Output
5. Delete lines containing 'Linux'
Command:
sed '/Linux/d' [Link]
Output:
Line one: Hello World
Line three: sed is powerful
Line five: Goodbye
6. Insert a line before line 3
Command:
sed '3i This is an inserted line' [Link]
Output:
Line one: Hello World
Line two: Welcome to Linux
This is an inserted line
Line three: sed is powerful
Line four: Learn Linux
Line five: Goodbye
7. Append a line after line 2
Command:
sed '2a This is an appended line' [Link]
Output:
Line one: Hello World
Line two: Welcome to Linux
This is an appended line
Line three: sed is powerful
Line four: Learn Linux
Line five: Goodbye
8. Replace 'Linux' with 'Unix' only on line 4
Command:
sed '4s/Linux/Unix/' [Link]
Output:
Line one: Hello World
Line two: Welcome to Linux
Line three: sed is powerful
Line four: Learn Unix
Line five: Goodbye
sed Command in Linux/Unix - Examples and Output
9. Multiple commands - replace 'Hello' on line 1 and delete line 5
Command:
sed -e '1s/Hello/Hi/' -e '5d' [Link]
Output:
Line one: Hi World
Line two: Welcome to Linux
Line three: sed is powerful
Line four: Learn Linux
10. Save output to new file after replacing 'Linux' with 'Unix'
Command:
sed 's/Linux/Unix/g' [Link] > [Link]
This saves the output to [Link] without modifying the original.