How to Use sed to Replace Brackets (With Example)


Often you may want to use sed to replace brackets in a string.

You can use the following syntax to do so:

sed 's/[][]/ /g' id_list.txt

This particular example replaces brackets with spaces in each line of the file named id_list.txt.

Here is how this syntax works:

  • We use the s command to “substitute” one pattern for another.
  • We use outer brackets [  ] to specify individual characters we would like to replace, e.g. using [AB] would replace the characters “A” and “B” specifically.
  • By using [][] we specify that we would like to replace all occurrences of ] and [ in each line.
  • We use the g flag to specify that this substitution should be made “globally”, i.e. for all occurrences.

The following example shows how to use this syntax in practice.

Example: How to Use sed to Replace Brackets

Suppose that we have a file named id_list.txt that contains the ID values for various employees at some company.

We can use the cat command to view the contents of this file:

Suppose that we would like to replace the brackets in each line with spaces instead.

We can use the following syntax to do so:

sed 's/[][]/ /g' id_list.txt

The following screenshot shows how to use this syntax in practice:

sed replace brackets with spaces

Notice that the brackets have been replaced with spaces in each line of the file.

Note that we could also specify nothing as the replacement pattern to instead simply remove the brackets from each line:

sed 's/[][]//g' id_list.txt

The following screenshot shows how to use this syntax in practice:

sed remove brackets

Notice that the brackets have simply been removed from each line in the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Replace nth Occurrence of Pattern
How to Use sed to Replace Last Line Matching Pattern
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply