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












1














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




















  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    Dec 9 at 5:40










  • @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
    Dec 9 at 5:58












  • 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
    Dec 9 at 6:01










  • @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
    Dec 9 at 6:05












  • 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
    Dec 9 at 6:42
















1














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




















  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    Dec 9 at 5:40










  • @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
    Dec 9 at 5:58












  • 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
    Dec 9 at 6:01










  • @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
    Dec 9 at 6:05












  • 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
    Dec 9 at 6:42














1












1








1







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















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















share|improve this question













share|improve this question




share|improve this question








edited Dec 9 at 8:41









Sparhawk

9,27363991




9,27363991










asked Dec 9 at 5:36









satyaki

122




122








  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    Dec 9 at 5:40










  • @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
    Dec 9 at 5:58












  • 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
    Dec 9 at 6:01










  • @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
    Dec 9 at 6:05












  • 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
    Dec 9 at 6:42














  • 2




    What have you tried? This is very easy to do.
    – Nasir Riley
    Dec 9 at 5:40










  • @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
    Dec 9 at 5:58












  • 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
    Dec 9 at 6:01










  • @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
    Dec 9 at 6:05












  • 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
    Dec 9 at 6:42








2




2




What have you tried? This is very easy to do.
– Nasir Riley
Dec 9 at 5:40




What have you tried? This is very easy to do.
– Nasir Riley
Dec 9 at 5:40












@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
Dec 9 at 5:58






@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
Dec 9 at 5:58














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
Dec 9 at 6:01




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
Dec 9 at 6:01












@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
Dec 9 at 6:05






@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
Dec 9 at 6:05














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
Dec 9 at 6:42




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
Dec 9 at 6:42










2 Answers
2






active

oldest

votes


















5














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
    Dec 9 at 6:38






  • 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
    Dec 9 at 8:28





















2














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',
    autoActivateHeartbeat: false,
    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
    });


    }
    });














    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









    5














    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
      Dec 9 at 6:38






    • 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
      Dec 9 at 8:28


















    5














    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
      Dec 9 at 6:38






    • 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
      Dec 9 at 8:28
















    5












    5








    5






    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 Dec 9 at 8:27

























    answered Dec 9 at 6:34









    jimmij

    30.8k870105




    30.8k870105












    • Nice +1. Much simpler than awk.
      – Sparhawk
      Dec 9 at 6:38






    • 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
      Dec 9 at 8:28




















    • Nice +1. Much simpler than awk.
      – Sparhawk
      Dec 9 at 6:38






    • 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
      Dec 9 at 8:28


















    Nice +1. Much simpler than awk.
    – Sparhawk
    Dec 9 at 6:38




    Nice +1. Much simpler than awk.
    – Sparhawk
    Dec 9 at 6:38




    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
    Dec 9 at 8:28






    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
    Dec 9 at 8:28















    2














    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


























      2














      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
























        2












        2








        2






        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 Dec 9 at 5:49









        Sparhawk

        9,27363991




        9,27363991






























            draft saved

            draft discarded




















































            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

            How to change which sound is reproduced for terminal bell?

            Can I use Tabulator js library in my java Spring + Thymeleaf project?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents