Using string replacement

The s command performs string replacement in the indicated lines in the input file.

If the command finds a set of characters in the input file that satisfies the regular expression Pattern, it replaces the set of characters with the set of characters specified in String.

The String parameter is a literal set of characters (digits, letters and symbols). Two special symbols can be used in String:

Symbol Use
& This symbol in String is replaced by the set of characters in the input lines that matched Pattern. For example, the command:
s/boy/&s/
tells sed to find a pattern boy in the input line, and copy that pattern to the output with an appended s. Therefore, it changes the input line:
From:
The boy look at the game.
To:
The boys look at the game.
Symbol Use
\d d is a single digit. This symbol in String is replaced by the set of characters in the input lines that matches the dth substring in Pattern. Substrings begin with the characters \( and end with the characters\ ). For example, the command:
s/\(stu\)\(dy\)/\1r\2/
From:
The study chair
To:
The sturdy chair

The letters that appear as flags change the replacement as follows:

Symbol Use
g Substitutes String for all instances of Pattern in the indicated line(s). Characters in String are not scanned for a match of Pattern after they are inserted. For example, the command:
s/r/R/g

changes:

From:
the red round rock
To:
the Red Round Rock
p Prints (to STDOUT) the line that contains a successfully matched Pattern.
w FileName Writes to FileName the line that contains a successfully matched Pattern. if FileName exists, it is overwritten; otherwise, it is created. A maximum of 10 different files can be mentioned as input or output files in the entire editing process. Include exactly one space between w and FileName.