File search and replace

To use shell script regular expressions to search and replace files, you can use the “sed” command.

sed is a text stream editor that can be used to make file replacements. To use sed, you need to specify the regular expression you want to fetch and the string you want to replace it with.

The general syntax of the sed command for search and replace is as follows:

sed ‘s/pattern/replacement/g’ file

Where:

  • “pattern” is the regular expression you want to fetch;
  • “replacement” is the string you want to replace with the pattern;
  • “g” is an option that indicates that all occurrences of the pattern are to be replaced;
  • “file” is the name of the file you want to replace.

Por exemplo, suponha que você queira substituir todas as ocorrências da palavra “casa” pela palavra “apartamento” no arquivo “arquivo.txt”. Você pode fazer isso com o seguinte comando:

sed ‘s/house/apartment/g’ file.txt

In addition, “sed” supports a wide variety of regular expressions that can be used to search for more complex patterns, such as:

  • “[a-z]”: search for any character from a to z;
  • “^”: search for the beginning of the line;
  • “$”: search for the end of the line;
  • “.”: search for any character;
  • “*”: search for zero or more occurrences of the previous pattern;
  • “+”: search for one or more occurrences of the previous pattern;
  • “\”: used to escape special characters like ., $, ^, etc.

For example, the following command searches for lines that begin with the word “error” and contain the word “system”:

sed -n ‘/^error.*system/p’ file.txt

In this example, the “-n” option is used to suppress the standard output of “sed”, and the regular expression “/^error.*system/p” is used to search for lines that start with “error” and contain “system “. The “p” option is used to print the lines that match the pattern.