0

I have to insert some text after matching a pattern in between a line.

  core: [dev][delta3=deltafile;delta3dir=755|workpm][staging=stageingfile]

  Expected output is:

  core: [dev][delta3=deltafile;delta3dir=755|workpm][delta6=delta6file;delta6Dir=755|workpm][staging=stageingfile]

Now what I tried is below: But this is not working as expected

 sed -i 's/\<[delta3=deltafile;delta3dir=755|workpm]\>/& [delta6=delta6file;delta6Dir=755|workpm]/' file.txt

This is editing my file but [delta6...] entry gets appended abruptly after

File data is like: asdasdasdad   B-L-D-V-E-R

output is showing: asdadasdadd B-L-D-[delta6=delta6file;delta6Dir=755|workpm] -V-E-R
0

You need to escape the | and the opening bracket [ as these are special characters in regex.

Also, you use word boundary matching \< and \> which you don't need and might cause problems.

But still then for me it only works using sed -E (not sure yet why ...).

sed -Ei 's/\[delta3=deltafile;delta3dir=755\|workpm]/&[delta6=delta6file;delta6Dir=755|workpm]/' file.txt

or if your sed does not support & back-reference:

sed -Ei 's/(\[delta3=deltafile;delta3dir=755\|workpm])/\1[delta6=delta6file;delta6Dir=755|workpm]/' file.txt

Output:

$ echo "core: [dev][delta3=deltafile;delta3dir=755|workpm][staging=stageingfile]" \
| sed -E 's/\[delta3=deltafile;delta3dir=755\|workpm]/&[delta6=delta6file;delta6Dir=755|workpm]/'
core: [dev][delta3=deltafile;delta3dir=755|workpm][delta6=delta6file;delta6Dir=755|workpm][staging=stageingfile]
  • maybe someone can point me to why it's only working with -E ... without it, the |workpm is excluded from the match. – pLumo May 8 at 12:23
  • Thanks it worked. Issue was I was giving the pattern to match inside /\< pattern\>/ – Anish Gupta May 8 at 13:05
  • glad that it works now :-) – pLumo May 8 at 13:12
  • let's clean up the comments as they are not so useful for next users I think – pLumo May 8 at 13:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.