How to replace a string when another string is found in a line?











up vote
1
down vote

favorite












I want to replace a string 'xy' with another string 'ab' when string 'ny' is found in a line of a unix file.



Sample text:



If we have xy today we can go to ny.
If we have xy tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.


Output text should look like:-



If we have ab today we can go to ny.
If we have ab tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.









share|improve this question









New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    20 hours ago










  • @G-Man We don't have a sample of the file but if he just wants to replace a string on lines where anther appears then he can just use grep to print the lines where ny appears and then use sed to replace xy with ab.
    – Nasir Riley
    20 hours ago












  • ISTM that the question that that answers is a rather twisted interpretation of the question that the OP asked. The output would be a subset of the input file, with the desired changes made in those lines.
    – G-Man
    20 hours ago










  • @G-man What it seems to you could also be entirely different than what is being asked because he hasn't provided a sample of the contents of the file or the expected output. Until we have that, all we can go on its what we think is wanted which is why I haven't posted an answer.
    – Nasir Riley
    20 hours ago












  • satyaki: You have given an example for the question "I want to replace a string 'xy' with another string 'ab' in every line of a file."   Since the string 'ny' is found in every line of your input, you aren't demonstrating what's supposed to happen with lines that don't contain it.
    – G-Man
    19 hours ago















up vote
1
down vote

favorite












I want to replace a string 'xy' with another string 'ab' when string 'ny' is found in a line of a unix file.



Sample text:



If we have xy today we can go to ny.
If we have xy tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.


Output text should look like:-



If we have ab today we can go to ny.
If we have ab tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.









share|improve this question









New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    20 hours ago










  • @G-Man We don't have a sample of the file but if he just wants to replace a string on lines where anther appears then he can just use grep to print the lines where ny appears and then use sed to replace xy with ab.
    – Nasir Riley
    20 hours ago












  • ISTM that the question that that answers is a rather twisted interpretation of the question that the OP asked. The output would be a subset of the input file, with the desired changes made in those lines.
    – G-Man
    20 hours ago










  • @G-man What it seems to you could also be entirely different than what is being asked because he hasn't provided a sample of the contents of the file or the expected output. Until we have that, all we can go on its what we think is wanted which is why I haven't posted an answer.
    – Nasir Riley
    20 hours ago












  • satyaki: You have given an example for the question "I want to replace a string 'xy' with another string 'ab' in every line of a file."   Since the string 'ny' is found in every line of your input, you aren't demonstrating what's supposed to happen with lines that don't contain it.
    – G-Man
    19 hours ago













up vote
1
down vote

favorite









up vote
1
down vote

favorite











I want to replace a string 'xy' with another string 'ab' when string 'ny' is found in a line of a unix file.



Sample text:



If we have xy today we can go to ny.
If we have xy tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.


Output text should look like:-



If we have ab today we can go to ny.
If we have ab tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.









share|improve this question









New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I want to replace a string 'xy' with another string 'ab' when string 'ny' is found in a line of a unix file.



Sample text:



If we have xy today we can go to ny.
If we have xy tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.


Output text should look like:-



If we have ab today we can go to ny.
If we have ab tomorrow we can go to ny tomorrow.
If we have mn now we can go to ny now.






linux text-processing sed grep






share|improve this question









New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 17 hours ago









Sparhawk

9,11063889




9,11063889






New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 20 hours ago









satyaki

122




122




New contributor




satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






satyaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    20 hours ago










  • @G-Man We don't have a sample of the file but if he just wants to replace a string on lines where anther appears then he can just use grep to print the lines where ny appears and then use sed to replace xy with ab.
    – Nasir Riley
    20 hours ago












  • ISTM that the question that that answers is a rather twisted interpretation of the question that the OP asked. The output would be a subset of the input file, with the desired changes made in those lines.
    – G-Man
    20 hours ago










  • @G-man What it seems to you could also be entirely different than what is being asked because he hasn't provided a sample of the contents of the file or the expected output. Until we have that, all we can go on its what we think is wanted which is why I haven't posted an answer.
    – Nasir Riley
    20 hours ago












  • satyaki: You have given an example for the question "I want to replace a string 'xy' with another string 'ab' in every line of a file."   Since the string 'ny' is found in every line of your input, you aren't demonstrating what's supposed to happen with lines that don't contain it.
    – G-Man
    19 hours ago














  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    20 hours ago










  • @G-Man We don't have a sample of the file but if he just wants to replace a string on lines where anther appears then he can just use grep to print the lines where ny appears and then use sed to replace xy with ab.
    – Nasir Riley
    20 hours ago












  • ISTM that the question that that answers is a rather twisted interpretation of the question that the OP asked. The output would be a subset of the input file, with the desired changes made in those lines.
    – G-Man
    20 hours ago










  • @G-man What it seems to you could also be entirely different than what is being asked because he hasn't provided a sample of the contents of the file or the expected output. Until we have that, all we can go on its what we think is wanted which is why I haven't posted an answer.
    – Nasir Riley
    20 hours ago












  • satyaki: You have given an example for the question "I want to replace a string 'xy' with another string 'ab' in every line of a file."   Since the string 'ny' is found in every line of your input, you aren't demonstrating what's supposed to happen with lines that don't contain it.
    – G-Man
    19 hours ago








2




2




What have you tried? This is very easy to do.
– Nasir Riley
20 hours ago




What have you tried? This is very easy to do.
– Nasir Riley
20 hours ago












@G-Man We don't have a sample of the file but if he just wants to replace a string on lines where anther appears then he can just use grep to print the lines where ny appears and then use sed to replace xy with ab.
– Nasir Riley
20 hours ago






@G-Man We don't have a sample of the file but if he just wants to replace a string on lines where anther appears then he can just use grep to print the lines where ny appears and then use sed to replace xy with ab.
– Nasir Riley
20 hours ago














ISTM that the question that that answers is a rather twisted interpretation of the question that the OP asked. The output would be a subset of the input file, with the desired changes made in those lines.
– G-Man
20 hours ago




ISTM that the question that that answers is a rather twisted interpretation of the question that the OP asked. The output would be a subset of the input file, with the desired changes made in those lines.
– G-Man
20 hours ago












@G-man What it seems to you could also be entirely different than what is being asked because he hasn't provided a sample of the contents of the file or the expected output. Until we have that, all we can go on its what we think is wanted which is why I haven't posted an answer.
– Nasir Riley
20 hours ago






@G-man What it seems to you could also be entirely different than what is being asked because he hasn't provided a sample of the contents of the file or the expected output. Until we have that, all we can go on its what we think is wanted which is why I haven't posted an answer.
– Nasir Riley
20 hours ago














satyaki: You have given an example for the question "I want to replace a string 'xy' with another string 'ab' in every line of a file."   Since the string 'ny' is found in every line of your input, you aren't demonstrating what's supposed to happen with lines that don't contain it.
– G-Man
19 hours ago




satyaki: You have given an example for the question "I want to replace a string 'xy' with another string 'ab' in every line of a file."   Since the string 'ny' is found in every line of your input, you aren't demonstrating what's supposed to happen with lines that don't contain it.
– G-Man
19 hours ago










2 Answers
2






active

oldest

votes

















up vote
5
down vote













sed is probably the simplest approach:



sed '/ny/s/xy/ab/g' file


It contains two sub-commands: /ny/ searches for a pattern, and s/xy/ab/g does actual substitution. Notice that it will replace all occurrences of xy; if you want to replace only first of them in each line just remove final g.






share|improve this answer























  • Nice +1. Much simpler than awk.
    – Sparhawk
    19 hours ago






  • 2




    Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
    – Kusalananda
    17 hours ago




















up vote
2
down vote













An answer in awk:



awk '/ny/ {gsub(/xy/,"ab")}; {print}' test.txt


Explanation





  • /ny/: only do the following commands when there is ny on the line.


  • gsub(/xy/,"ab"): substitute /xy/ with ab, only on those lines.


  • {print}: regardless of what line you are on, print the line.






share|improve this answer





















    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "106"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });






    satyaki is a new contributor. Be nice, and check out our Code of Conduct.










    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f486889%2fhow-to-replace-a-string-when-another-string-is-found-in-a-line%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    5
    down vote













    sed is probably the simplest approach:



    sed '/ny/s/xy/ab/g' file


    It contains two sub-commands: /ny/ searches for a pattern, and s/xy/ab/g does actual substitution. Notice that it will replace all occurrences of xy; if you want to replace only first of them in each line just remove final g.






    share|improve this answer























    • Nice +1. Much simpler than awk.
      – Sparhawk
      19 hours ago






    • 2




      Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
      – Kusalananda
      17 hours ago

















    up vote
    5
    down vote













    sed is probably the simplest approach:



    sed '/ny/s/xy/ab/g' file


    It contains two sub-commands: /ny/ searches for a pattern, and s/xy/ab/g does actual substitution. Notice that it will replace all occurrences of xy; if you want to replace only first of them in each line just remove final g.






    share|improve this answer























    • Nice +1. Much simpler than awk.
      – Sparhawk
      19 hours ago






    • 2




      Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
      – Kusalananda
      17 hours ago















    up vote
    5
    down vote










    up vote
    5
    down vote









    sed is probably the simplest approach:



    sed '/ny/s/xy/ab/g' file


    It contains two sub-commands: /ny/ searches for a pattern, and s/xy/ab/g does actual substitution. Notice that it will replace all occurrences of xy; if you want to replace only first of them in each line just remove final g.






    share|improve this answer














    sed is probably the simplest approach:



    sed '/ny/s/xy/ab/g' file


    It contains two sub-commands: /ny/ searches for a pattern, and s/xy/ab/g does actual substitution. Notice that it will replace all occurrences of xy; if you want to replace only first of them in each line just remove final g.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 17 hours ago

























    answered 19 hours ago









    jimmij

    30.5k869103




    30.5k869103












    • Nice +1. Much simpler than awk.
      – Sparhawk
      19 hours ago






    • 2




      Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
      – Kusalananda
      17 hours ago




















    • Nice +1. Much simpler than awk.
      – Sparhawk
      19 hours ago






    • 2




      Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
      – Kusalananda
      17 hours ago


















    Nice +1. Much simpler than awk.
    – Sparhawk
    19 hours ago




    Nice +1. Much simpler than awk.
    – Sparhawk
    19 hours ago




    2




    2




    Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
    – Kusalananda
    17 hours ago






    Strictly speaking /ny/ is not a command but the address for the following s command (this could also have been a line number or a range of lines between two regular expressions or numbers).
    – Kusalananda
    17 hours ago














    up vote
    2
    down vote













    An answer in awk:



    awk '/ny/ {gsub(/xy/,"ab")}; {print}' test.txt


    Explanation





    • /ny/: only do the following commands when there is ny on the line.


    • gsub(/xy/,"ab"): substitute /xy/ with ab, only on those lines.


    • {print}: regardless of what line you are on, print the line.






    share|improve this answer

























      up vote
      2
      down vote













      An answer in awk:



      awk '/ny/ {gsub(/xy/,"ab")}; {print}' test.txt


      Explanation





      • /ny/: only do the following commands when there is ny on the line.


      • gsub(/xy/,"ab"): substitute /xy/ with ab, only on those lines.


      • {print}: regardless of what line you are on, print the line.






      share|improve this answer























        up vote
        2
        down vote










        up vote
        2
        down vote









        An answer in awk:



        awk '/ny/ {gsub(/xy/,"ab")}; {print}' test.txt


        Explanation





        • /ny/: only do the following commands when there is ny on the line.


        • gsub(/xy/,"ab"): substitute /xy/ with ab, only on those lines.


        • {print}: regardless of what line you are on, print the line.






        share|improve this answer












        An answer in awk:



        awk '/ny/ {gsub(/xy/,"ab")}; {print}' test.txt


        Explanation





        • /ny/: only do the following commands when there is ny on the line.


        • gsub(/xy/,"ab"): substitute /xy/ with ab, only on those lines.


        • {print}: regardless of what line you are on, print the line.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 20 hours ago









        Sparhawk

        9,11063889




        9,11063889






















            satyaki is a new contributor. Be nice, and check out our Code of Conduct.










            draft saved

            draft discarded


















            satyaki is a new contributor. Be nice, and check out our Code of Conduct.













            satyaki is a new contributor. Be nice, and check out our Code of Conduct.












            satyaki is a new contributor. Be nice, and check out our Code of Conduct.
















            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f486889%2fhow-to-replace-a-string-when-another-string-is-found-in-a-line%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mont Emei

            Province de Neuquén

            Journaliste