0

I have a string which has a format like this :

{u city : u Zurich , u name : u Hauptbahnhof , u address : u Test address, C106, Bahnhofsstrasse }

I need to remove all the " u " (with the spaces) and replace the ", u "(with the spaces) with a line breaker, but i have no idea how i could do that.

Is it possible with sed?

Output should be like

{city :Zurich 
name :Hauptbahnhof 
address :Test address, C106, Bahnhofsstrasse }

Thank you guys

2
  • Where did you obtain said string? To me it seems like an attempt to create JSON from Python, if so go fix your Python code. Commented Dec 16, 2016 at 8:57
  • it's from a json output which has been altered, but i have to use it like this unfortunately Commented Dec 16, 2016 at 8:59

2 Answers 2

2

The following seems to work (with some whitespace differences):

's/, u /\n/g;s/\bu //g'

i.e. first replace all ", u " with newlines, then remove all u, where u is not preceded by a word character.

Note that the output isn't a valid JSON.

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

7 Comments

This is really fragile, as any word ending with u will get it removed.
@andlrc: fixed.
i get the error "unterminated `s' command" i use sed -e and i use it after a pipe, maybe that helps..
@Damon: please show the whole line. Also, what OS and sed version?
cat silo_json | sed -e 's/, u /\n/g;s/\bu //g' RHEL 6.8 GNU sed version 4.2.1
|
1

Use perl command line substitution as below, used the \b tags for matching exact words and not mess up with other strings.

perl -pe 's/\bu \b//g;' -pe 's/\b , \b/\n/g;' file
{city : Zurich
name : Hauptbahnhof
address : Test address, C106, Bahnhofsstrasse }

And as pointed by others, if it is a broken JSON use jq or other ways to fix it.

4 Comments

same problem as above i get the error "unterminated `s' command" i have to use the string like that and output doesn't need to be json
i used a tmp-file for your example to check if it works
.. my mistake i forgot to remove a sed statement in the script, your solution works perfectly.
yeah sure, sorry that i gave him the solution but his worked too and he brought it up first, but thanks again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.