sed command is stream editor for filtering and transforming text.
cheulong@master-node:~$ cat hawaii-pizza.txt Ingredients: 1. Flour 2. Mozzarella 3. Cheese 4. Ham 5. Pizza sauce 6. Pineapple Pineapple
Let replace pineapple from the list
# file doesn't change, only output sed 's/Pineapple/Feta/' hawaii-pizza.txt --- Ingredients: 1. Flour 2. Mozzarella 3. Cheese 4. Ham 5. Pizza sauce 6. Feta Pineapple
By default, the sed command replaces the first occurrence of the pattern in each line
Replace
To replacing the nth occurrence of a pattern in a Line
sed 's/Pineapple/Feta/2' hawaii-pizza.txt # All occurrence sed 's/Pineapple/Feta/g' hawaii-pizza.txt # second occurrence to all occurrence sed 's/Pineapple/Feta/2g' hawaii-pizza.txt
Change in-place
# replace string sed -i 's/Pineapple/Feta/' hawaii-pizza.txt
Replacing String on a Specific Line Number
sed '3 s/./!/' hawaii-pizza.txt
Printing Only the Replaced Lines
sed -n 's/Pineapple/Feta/' hawaii-pizza.txt
Replacing String on a Range of Lines
sed '1,3 s/./!/' hawaii-pizza.txt # from line 2 to last sed '2,$ s/./!/' hawaii-pizza.txt
Delete
Remove something
sed 's/Feta//' hawaii-pizza.txt --- Ingredients: 1. Flour 2. Mozzarella 3. Cheese 4. Ham 5. Pizza sauce 6.
Delete Line
sed '2d' hawaii-pizza.txt
Delete Last Line
sed '$d' hawaii-pizza.txt
To Delete line from range x to y
sed '4,$d' hawaii-pizza.txt
Insert
Insert Text
sed '3i\Break' hawaii-pizza.txt # Insert text before line 3 sed '3a\Break' hawaii-pizza.txt # Insert text after line 3
Best Practices
- Be sure to back up your files before applying for the changes. (especially while using -i)
- Be careful before using regular expressions to avoid any unintended change.
- Always test your SED command on sample file first before using it to avoid unintentional change.
Leave a comment if you have any questions.
===========
Please keep in touch
Portfolio
Linkedin
Github
Youtube
Top comments (0)