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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityI 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.
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
.
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
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