1

I have a file that I need to replace all matches below:

,"   "\n  to  ,"ZYY"\n
,"ZZY"\n  to  ,"ZYY"\n
,"GMZ"\n  to  ,"FPZ"\n

I'm trying to use the command: sed 's/," "/,"ZYY"/g' Packs.txt but it is not working.

  • 2
    Please define not working. The syntax seems ok. – Rui F Ribeiro Oct 22 '18 at 17:08
  • When i run the command, don't replace as i wish. – Pedro Lopes Oct 22 '18 at 17:50
  • That is the definition of "not working (as you intend)". What exactly is the result, and how is it different from what you intend? – RalfFriedl Oct 22 '18 at 22:22
2

This appears to do the trick:

$ sed -E 's/,"(   |ZZY)"$/,"ZYY"/;s/,"GMZ"$/,"FPZ"/' inputfile

The main thing here is using the $ anchor to mark the end of the line, rather than searching for a \n.

2

If you have a collection of conversions you need to do, you can put them into a file. You can then use the "-f _sed_file_" to process all of them. For example, if you input file is something like this test.in file:

This,"   ",is,a,test
This,too,"ZZY",is,a,test
And,so,"GMZ",is,this

And you have the following sed file:

s/,"   "/,"ZYY"/g
s/,"ZZY"/,"ZYY"/g
s/,"GMZ"/,"FPZ"/g

You can run the following command:

sed -f test.sed test.in

To get the following output:

This,"ZYY",is,a,test
This,too,"ZYY",is,a,test
And,so,"FPZ",is,this
  • Will fail with an unexpected replacement for cases not at the end of the line as described in the question. – DopeGhoti Oct 22 '18 at 18:34
0

This will change all three strings to what you desire and only send the changes to standard output:

 sed -e 's|,"   "\\n|,"ZYY"\\n|g' -e 's|,"ZZY"\\n|,"ZYY"\\n|g' -e 's|,"GMZ"\\n|,"FPZ"\\n|g' Packs.txt

I used the entire strings and not just the letters between the double quotes as you didn't specify whether those specific strings appear anywhere else in the file.

Once you are satisfied with the outcome, you can use the below command to change the file itself.

sed -i -e 's|,"   "\\n|,"ZYY"\\n|g' -e 's|,"ZZY"\\n|,"ZYY"\\n|g' -e 's|,"GMZ"\\n|,"FPZ"\\n|g' Packs.txt

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.