Sed
Sed
Sed is a powerful text processing tool that can be used to perform basic
text transformations on an input stream.
s → substitute
y → transform.
$sed -n ' ' file → does not print any lines by default. Silence mode.
Case 1: writing the script in the command line using the option $sed -e
$sed '4d ; 7d' test.txt → delete the 4th line and the 7th line.
Sed dressing patterns (motif /fr) are used to perform operations on text
files in Linux.
/regex/
Sed '/^# / d' test.txt → delete all lines starting with '#'
2. If only the /motif1/ sed will apply the command line in all lines
starting from '/motif1/'. Exemple: sed '/linux/,$d' sed.txt #pay
attention to $ before d.
3. We can use $sed '3,/^bonjour/ d' sed.txt to delete all lines from the
3rd line until the first line starting with 'bonjour'.
The p {print} command prints the selected line. The -n flag suppresses
automatic printing, so you need to use the p command to print the selected
line.
Examples ;
4. $sed -n '/^tu /p' sed.txt → print lines that start with "tu".
The l {list} command and = ; the l command is used to display each line of
the file with non-printing characters visibly represented. It is often used
for debugging or for viewing special characters.
Examples ;
1. sed -n 'l' sed.txt is used to view the special characters in the file.
Examples ;
Output; 1
bonjour
Examples ;
1. $sed '4d ; 7d' sed.txt → This command deletes lines 4 and 7 from the
file sed.txt.
2. $sed '/^linux /d' sed.txt → This command deletes all lines that start
with the word "linux" from the file sed.txt.
4. $sed '1d ; /^bonjour /d' sed.txt → This command deletes the first line
and any line that starts with "bonjour" in the file sed.txt.
Exemples ;
4. $sed -re 's/^# *//' sed.txt → removes all leading spaces and pound
signs from each line in the file sed.txt. * is a special character in
regular expressions that matches zero or more occurrences of the
preceding element.
5. $sed -re 's/ / /g' sed.txt → replaces all spaces with 6 additional
spaces in the file sed.txt.
6. $sed -z 's/\n/ /g' sed.txt → replaces all newlines with two additional
spaces in the file sed.txt. -z is used to change the line separator.
The y {transform};
Exemple;
Exemples;
1. $sed '3i bonjouuuuuuur' sed.txt → inserts the text "bonjouuuuuuur" on
line 3 of the file sed.txt.
Exemple;
1. $sed '8a hello' sed.txt → appends the text "hello" after line 8 in the
file sed.txt.
Exemple;
1. $sed '10c goodbye' sed.txt → changes the text on line 10 in the file
sed.txt to "goodbye".
Address denial using ! . $sed '/linux/!c unix' sed.txt → changes any line
not containing "linux" in the file sed.txt to "unix".
r {read} → reads the contents of a file and appends them to the output
stream.