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.

3
  • 2
    Please define not working. The syntax seems ok. Oct 22, 2018 at 17:08
  • When i run the command, don't replace as i wish. Oct 22, 2018 at 17:50
  • 1
    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, 2018 at 22:22

3 Answers 3

3

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
1
  • Will fail with an unexpected replacement for cases not at the end of the line as described in the question.
    – DopeGhoti
    Oct 22, 2018 at 18:34
1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .