0

If I have string:

path1=/path/me & you/file.json&path2=/path/you & me/file.txt

I expect the output to be like this:

path1=/path/me & you/file.json;path2=/path/you & me/file.txt

I need to replace & that it's front and back not contain space, I tried with sed but I keep got this

path1=/path/me ; you/file.json;path2=/path/you ; me/file.txt

2
  • Are you actually trying to parse URL query parameters? Commented Jan 10, 2019 at 3:22
  • Your question should really include the sed script you tried, and perhaps explain your thinking behind it. Commented Jan 10, 2019 at 3:29

3 Answers 3

1

You can use [^ ] to match a non-space character and make sure it's in a \(capture group\) so that you can reference it in the replacement string:

sed -e 's/\([^ ]\)&\([^ ]\)/\1;\2/'

This finds any three character sequence of non-space & non-space and replaces it just the two captured characters, effectively replacing any & without a space next to it.

This will affect foo&bar but not foo & bar or foo& bar or &foo

Sign up to request clarification or add additional context in comments.

1 Comment

The OP's expectation would be: sed -e 's/\([^ ]\)&\([^ ]\)/\1;\2/'. You may have overlooked the semicolon in between.
0

I'm guessing maybe you are looking for

sed 's/&\([a-z][a-z0-9]*=\)/;\1/g'

i.e. replace only semicolons which are immediately followed by a token and an equals sign. (You may have to adjust the token definition, depending on what your tokens can look like. For example, underscore is often supported, but rarely used. You mght want to support uppercase, too.)

If at all possible, fix the process which produces these values, as the format is inherently ambiguous.

Comments

0
sed -r 's/(\S)&(\S)/\1;\2/g'

Where -r enable regex and \S is all except spaces.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.