DEV Community

Cover image for Basic Linux command (sed)
Cheulong Sear
Cheulong Sear

Posted on

Basic Linux command (sed)

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Change in-place

# replace string
sed -i 's/Pineapple/Feta/' hawaii-pizza.txt
Enter fullscreen mode Exit fullscreen mode

Replacing String on a Specific Line Number

sed '3 s/./!/' hawaii-pizza.txt
Enter fullscreen mode Exit fullscreen mode

Printing Only the Replaced Lines

sed -n 's/Pineapple/Feta/' hawaii-pizza.txt
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Delete

Remove something

sed 's/Feta//' hawaii-pizza.txt
---
Ingredients:
1. Flour
2. Mozzarella
3. Cheese
4. Ham
5. Pizza sauce
6. 
Enter fullscreen mode Exit fullscreen mode

Delete Line

sed '2d' hawaii-pizza.txt
Enter fullscreen mode Exit fullscreen mode

Delete Last Line

sed '$d' hawaii-pizza.txt
Enter fullscreen mode Exit fullscreen mode

To Delete line from range x to y

sed '4,$d' hawaii-pizza.txt
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)