Substitution – the s command

If we want to substitute some text with new text, then we can use commands. After the forward slash, the regular expression is enclosed and then the text to be substituted is placed. If the g option is used, then substitution will happen globally, meaning that it will be applied to the full document. Otherwise, only the first instance will be substituted:

    $ cat shopping.txt
  

The output is as follows:

    Product     Quantity   Unit_Price  Total_Cost
    Apple       2           3          6
    Orange            2           .8         1.6
    Papaya            2           1.5        3
    Chicken     3           5          15
    Cashew       1           10         10
    $ sed 's/Cashew/Almonds/g' shopping.txt
  

The output is as follows:

    Product          Quantity   Unit_Price  Total_Cost 
    Apple       2           3           6
    Orange            2           .8         1.6
    Papaya            2           1.5         3
    Chicken     3           5          15
    Almonds     1           10          10
  

The s command has ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.