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.
  • 2
    What have you tried? This is very easy to do. – Nasir Riley Dec 9 '18 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 '18 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 '18 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 '18 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 '18 at 6:42
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.

  • Nice +1. Much simpler than awk. – Sparhawk Dec 9 '18 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 '18 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.

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.