sed command usage

Command sed means “Stream EDitor”. The format for searching and replacing is as below:

sed -i.bak s/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g build.gradle

Explanation: pass the -i  option to sed to make the changes inline and create a backup of the original file before it does the changes in-place. Without the .bak the command will fail on some platforms, such as Mac OSX.

If the STRING_TO_REPLACE contains some path separator, e.g. `/` , then you can replace the `/` separator with other delimiters, e.g. `|`, or `#` which can be distinguished with the path separator `/`.

As this is said official from GNU manual,

The syntax of the s (as in substitute) command is `s/REGEXP/REPLACEMENT/FLAGS`. The `/` characters may be uniformly replaced by any other single character1 within any given s command. The `/` character (or whatever other character is used in its stead) can appear in the `REGEXP` or `REPLACEMENT` only if it is preceded by a `\` character.

For example we have a file `build.gradle` having below content and want to replace the line of  `sdkRootDir`  with a new path.

``` groovy
// Modify this path according to your own path environment (absolute path is better).
project.ext {
sdkRootDir = "$projectDir/../../../../../android"

Then we, for example,  use `|`  as the delimiter between the REGEXP and the replacement and the sed command becomes:

sed -i.bak 's|.*sdkRootDir =.*|    sdkRootDir = "$projectDir/../../../../../path/to/new"|'  build.gradle

or in short:

sed -i.bak ‘s|/some/path|/alternate/path/|’ build.gradle

1. (The sed man page on OSX explicitly excludes the backslash  `\` and newline characters from the above qualification of “any other single character” )


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s