Terminal - sed command

From NoskeWiki
Jump to navigation Jump to search

About

This page is a child of: Terminal commands


The `sed` (Stream Editor) command in Unix and Linux is a powerful text-processing utility. It's commonly used for parsing and transforming text in data streams, files, and pipelines. `sed` can perform basic text transformations on an input stream (a file or input from a pipeline).

Common Arguments

  • -e script: Add the script to the commands to be executed.
  • -i[SUFFIX], --in-place[=SUFFIX]: Edit files in-place, optionally making backup with the specified suffix.
  • -n, --quiet, --silent: Suppress automatic printing of pattern space.
  • s: The substitute command, typically used in the form s/pattern/replacement/.

Piping Output to `echo`

The output of `sed` can be piped into other commands like `echo` for further processing or for display. This is particularly useful when you want to see the result of a `sed` operation without modifying the file directly.

Example:

echo "original text" | sed 's/original/replaced/'

In this example, `sed` takes the output of `echo`, replaces 'original' with 'replaced', and then outputs the transformed text.

Overwriting a File

One common use of `sed` is to make in-place edits to files using the `-i` option. This allows for modifying a file directly without the need to output to a new file and then rename it.

Example: Overwriting with Environment Variables

In scenarios where you need to replace placeholders in a file with environment variable values, `sed` can be used effectively. For instance, if you have a file with placeholders like ${MY_ENVIRONMENT} and ${PROJECT_ID}, and you want to replace these placeholders with the values of corresponding environment variables, you can use the following `sed` command:

sed -i "" -e "s/\${MY_ENVIRONMENT}/${MY_ENVIRONMENT}/g" -e "s/\${PROJECT_ID}/${PROJECT_ID}/g" backend.yaml

In this command:

  • -i "" edits the file in-place without creating a backup.
  • -e "s/\${MY_ENVIRONMENT}/${MY_ENVIRONMENT}/g" replaces all occurrences of ${MY_ENVIRONMENT} with the value of the MY_ENVIRONMENT environment variable.
  • -e "s/\${PROJECT_ID}/${PROJECT_ID}/g" does the same for ${PROJECT_ID}.

This is particularly useful in automated scripts and build processes, where dynamic values need to be inserted into configuration files or scripts.


Links