0

I have bunch of string like "{one}two", where "{one}" could be different and "two" is always the same. I need to replace original sting with "three{one}", "three" is also constant. It could be easily done with python, for example, but I need it to be done with shell tools, like sed or awk.

3
  • So you already have your regexp ready and you just want to know how to use sed with it? Commented Jul 30, 2014 at 19:04
  • 2
    Post a small sample input set and expected output. You question could mean any of several different things and that would help clarify. Commented Jul 30, 2014 at 19:21
  • did the string {one}two appears anywhere in your file? Commented Jul 30, 2014 at 19:25

7 Answers 7

2

If I understand correctly, you want:

{one}two --> three{one}
{two}two --> three{two}
{n}two   --> three{n}

SED with a backreference will do that:

echo "{one}two" | sed 's/\(.*\)two$/three\1/'

The search store all text up to your fixed string, and then replace with the your new string pre-appended to the stored text. SED is greedy by default, so it should grab all text up to your fixed string even if there's some repeat in the variable part (e.gxx`., {two}two will still remap to three{two} properly).

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

Comments

2

Using sed:

s="{one}two"
sed 's/^\(.*\)two/three\1/' <<< "$s"
three{one}

Comments

1
echo "XXXtwo" | sed -E 's/(.*)two/three\1/'

Comments

1

Here's a Bash only solution:

string="{one}two"
echo "three${string/two/}"

Comments

0
awk '{a=gensub(/(.*)two/,"three\\1","g"); print a}' <<< "{one}two"

Output:

three{one}

Comments

0
awk '/{.*}two/ { split($0,s,"}"); print "three"s[1]"}" }' <<< "{one}two"

does also output

three{one}

Here, we are using awk to find the correct lines, and then split on "}" (which means your lines should not contain more than the one to indicate the field).

Comments

0

Through GNU sed,

$ echo 'foo {one}two bar' | sed -r 's/(\{[^}]*\})two/three\1/g'
foo three{one} bar

Basic sed,

$ echo 'foo {one}two bar' | sed 's/\({[^}]*}\)two/three\1/g'
foo three{one} bar

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.