0

I have few files which contain a string like JOY_DOL_XXX at many places. Which I wanted to replace with another string with double quotes as "JOY.DOL.XXX", but here XXX can be anything e.g. MAN, CAT, DOG so in this case I wanted to write a script which replaced this accordingly without specifying it explicitly.

For example:

  JOY_DOL_MAN ==> "JOY.DOL.MAN"
  JOY_DOL_CAT ==> "JOY.DOL.CAT"

Could you please help me out, how shall I do it.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Are add **`"`** too before and after string **?** – Grijesh Chauhan Sep 22 '13 at 07:50
  • Is XXX always 3 characters? If `JOY_DOL_FOOBAR` appeared in your input, what would the desired output be - `"JOY.DOL.FOO"BAR` or `"JOY.DOL.FOOBAR"` or `JOY_DOL_FOOBAR` or something else? – Ed Morton Sep 22 '13 at 14:16

2 Answers2

2

Sed seems simplest:

sed 's|JOY_DOL_\(...\)|"JOY.DOL.\1"|g' file

Input:

JOY_DOL_MAN
JOY_DOL_CAT

Output:

"JOY.DOL.MAN"
"JOY.DOL.CAT"
  • \(...\) matches three characters. The are represented in the replacement as \1.
  • g would allow multiple matches to be replaced for every input pattern.
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • $ echo JOY_DOL_XXX | sed 's|JOY_DOL_\(...\)|"JOY.DOL.\1"|g' – user2803710 Sep 22 '13 at 07:59
  • By the way you forgot to add slashes to () in your sed command: `echo "JOY_DOL_XXX" | sed 's|JOY_DOL_\(...\)|"JOY.DOL.\1"|g'`. Still those would still work if you enable extended regular expression instead with `-E` or `-r` i.e. `sed -E 's|JOY_DOL_(...)|"JOY.DOL.\1"|g'` or `sed -r 's|JOY_DOL_(...)|"JOY.DOL.\1"|g`. It just depends on the version of sed. – konsolebox Sep 22 '13 at 08:08
0

This awk may work.

awk '{gsub(/_/,".");print "\""$0"\""}' file

awk -F_ '{$1=$1;print "\""$0"\""}' OFS=. file

To support more complex request.

echo ABC JOY_DOL_CAT XYZ | awk '{for (i=1;i<=NF;i++) {if (gsub(/_/,".",$i)) printf "\"%s\" ",$i; else printf "%s ",$i}print ""}'
ABC "JOY.DOL.CAT" XYZ
Jotne
  • 40,548
  • 12
  • 51
  • 55
  • I have another doubt here, $echo JOY_DOL_XXXX | sed 's|JOY_DOL_\(...\)|"JOY.DOL.\1"|g' Gives me output as "JOY.DOL.XXX"X. But I am expecting "JOY.DO.XXXX" Here XXX may be 3 character or more. Please suggest solution for this – user2803710 Sep 22 '13 at 22:49
  • I found the "awk" solution given above is working fine for this case. Thanks .. – user2803710 Sep 22 '13 at 22:56
  • I have noticed one more issue now. # echo ABC JOY_DOL_CAT XYZ | awk '{gsub(/_/,".");print "\""$0"\""}' OUTPUT: "ABC JOY.DOL.CAT XYZ", But I am expecting ABC "JOY.DOL.CAT" XYZ – user2803710 Sep 23 '13 at 23:42
  • This is normal. When you change request, you get different result. This may work for your last request, but not other. `echo ABC JOY_DOL_CAT XYZ | awk '{gsub(/_/,".");print $1,"\""$2"\"",$3}'` If you have another input, create a new post, and add a complete file. – Jotne Sep 24 '13 at 05:52
  • Added new example in original post. – Jotne Sep 24 '13 at 06:27