Home > Enterprise >  Remove single slash but not double slash from string using sed
Remove single slash but not double slash from string using sed

Time:12-07

the string I want to edit looks like this:

/word1 /word2 //word3

wanted output:

word1 word2 //word3

The following command deletes all slashes and it makes since it does so

str=`echo $str | sed -r 's/\///g'`

How do I delete only single slashes.

CodePudding user response:

You can use

str=$(sed -E 's~(/{2,})|/~\1~g' <<< "$str")

See the online demo:

#!/bin/bash
s='/word1 /word2 //word3'
sed -E 's~(/{2,})|/~\1~g' <<< "$s"
# => word1 word2 //word3

Note the -E option (as -r option) enables the POSIX ERE regex syntax. 's~(/{2,})|/~\1~g' matches and captures two or more consecutive slashes into Group 1 or only matches a single slash otherwise, and replaces the matches with the contents of Group 1 (thus, restoring multiple slashes in the output, only removing single ones).

If you want to replace single slashes with a space, you can use the following GNU sed:

perl -pe 's~(?<!/)/(?!/)~ ~g' <<< "$s"
## or
sed -E 's~(^|[^/])/($|[^/])~\1\n\2~g;s//\1\n\2/g;s/\n/ /g' <<< "$s"

See this online demo.

The perl command matches any / chars that are not immediately preceded ((?<!/)) nor followed ((?!/)) with a slash. The sed command preprocesses all single slashes ((^|[^/])/($|[^/]) matches and captures start of string or a non-slash char into Group 1, then matches a / and then captures end of string or a non-slash into Group 2), and replaces with Group 1 newline Group 2 values, i.e. isolates the single slashes by turning them into newlines, and then these newlines (as they never appear in the pattern space) are replaced with whatever you need (here, a space).

  • Related