0

I'm using sed and i have a file which contains

apple
orange
banana
orange

i want to insert "pear" after the 1st orange only . So the output should be something like this

apple
orange
pear
banana
orange

I used this sed option:

sed -i '0,/orange/a pear' filename

but this gives me a output something like this:

apple
pear
orange
pear
banana
orange

  • With GNU sed: `sed -e '1,/orange/{/orange/a pear' -e '}' file` – Cyrus Jan 26 '19 at 20:41
  • sed -e s/orange/orange\\npear/ < file should work on any sed. – Alain Merigot Jan 26 '19 at 20:44
  • Please provide only the append option of sed not the substitution one – Aditya Khowala Jan 26 '19 at 20:47
  • @AdityaKhowala Did the teacher provide any other instructions on this assignment besides the restriction to using only _append_? – John1024 Jan 26 '19 at 21:01
  • @John1024 actually this is not the actual file i have been working on , and because of that i have a restriction of not using substitution. – Aditya Khowala Jan 26 '19 at 21:04
  • @AdityaKhowala If you explain your restrictions more fully (including, for example, why you think _substitute_ won't work on the real file), you will likely get more and better answers. Good luck. – John1024 Jan 26 '19 at 21:09
  • Does this answer your question? [How to use sed to replace only the first occurrence in a file?](https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file) – rogerdpack Jan 02 '20 at 23:37

2 Answers2

5

This might work for you (GNU sed):

sed '0,/orange/!b;//a\pear' file

Focus on the range of lines from the start of the file 0 to the first occurrence of the string orange otherwise bail out. If the line contains the first occurrence of the string orange, append the string pear.

potong
  • 55,640
  • 6
  • 51
  • 83
0

Using Substitution

s/^orange$/&\npear/;tl;b;:l;{n;bl}

Using Append

/^orange$/ {
    a\
pear
    bl
}
b;:l;{n;bl}
Rafael
  • 7,605
  • 13
  • 31
  • 46