Progmar Marcin Załęczny

Language:

Sed by examples

File persons.txt used for demonstration purposes (no., name, birth year, height, weight):

 1. Piotr   1989    184 70.2
 2. Tomasz  1994    172 60.8
 3. Paweł   2003    104 48.4
 4. Marcin  1980    174 91.6
 5. Michał  1990    168 74.9
 6. Lucjan  2000    80  44.1
 7. Paweł   2000    124 60.2
 8. Rafał   1980    174 91.6
 9. Michał  1998    139 89.1
10. Damian  1994    170 68.2

Displays all rows from the persons.txt file. All rows containing word "Paweł" are displayed double: sed '/Paweł/ p' persons.txt

Displays only rows containing word "Paweł": sed -n '/Paweł/ p' persons.txt

Displays rows starting at second and ending at fourth: sed -n '2,4 p' persons.txt

Displays all rows but second, third and fourth: sed -n '2,4 !p' persons.txt

Displays first four rows (counterpart for: head -4 persons.txt): sed '4 q' persons.txt

Appends a row 'New row' after the third row and displays new content: sed '3 a New row' persons.txt

Prepends a row 'New row' before each row containing string '99' and displays new content: sed '/99/ i New row' persons.txt

Replaces 7th and 8th rows with new content (file persons.txt stays unmodified): sed '7,8 c New content' persons.txt

Replaces all rows containing string '99' with new two lines content: sed '/99/ c Linijka #1\nLinijka #2' persons.txt

Replaces each 'n' character with 'N' one and displays new content: sed 's/n/N/g' persons.txt

Replaces each 'n' character with 'N' one and displays only modified rows: sed -n 's/n/N/g p' persons.txt

Removes first row: sed '1 d' persons.txt

Adds four spaces at the beginning of each not empty line. Character '&' is replaced with matched string: sed 's/^./ &/' persons.txt or (works for every line): sed 's/^/ /' persons.txt

Removes spaces from the ending of each line: sed 's/ *$//'

Removes all \r characters (carriage return) and saves modified content to the file persons.txt: sed -i 's/\r//g' persons.txt

Removes all spaces from the beginning of each line and saves modified content to the file persons.txt: sed -i 's/^ *//' persons.txt

Prepends with a space character each line that starts with any character followed by a dot ('.') and saves modified content to the file persons.txt sed -i 's/^.\./ &/' persons.txt