2

I have a string that looks something like this.

<tag-name i-am-an-attribute="123" and-me-too="321">

All I want to do is replace the dashes into an underscore, but the tag-name should remain like it is.

Hope there are some regex guru's who can help me out.

[solution] In case someone needs this.
I ended up with a perl oneliner command
echo '<tag-name i-am-an-attribute="123" and-me-too="321">' | perl -pe 's/( \K[^*"]*)-/$1_/g;' | perl -pe 's/ / /g;'
results in

<tag-name i_am_an_attribute="123" and_me_too="321">
HamZa
  • 14,671
  • 11
  • 54
  • 75

2 Answers2

1

Using sed:

sed ':l;s/-\([^- ]*\)\( *=\)/_\1\2/g;tl' input

Gives:

<tag-name i_am_an_attribute="123" and_me_too="321">
perreal
  • 94,503
  • 21
  • 155
  • 181
0

With <tag-name i-am-an-attribute="123" and-me-too="321"> as a line in a file:-

read -r < file

fullstring=$(echo "${REPLY}" | sed s'@-name @-name:@')

field1=$(echo "${fullstring}" | cut -d':' f1)
field2=$(echo "${fullstring}" | cut -d':' f2)

fixedfield=$(echo "${field2}" | sed s'@-@_@'g)

echo "${field1} ${fixedfield}"

I'm discovering that the most important thing, with scripting, is to provide yourself anchors within the text, that you can use to cut it up into segments that you can then perform operations on. Try to format your text as actual fields with seperators; it makes life a lot easier.

petrus4
  • 616
  • 4
  • 7