0

I have this text file. I want to replace the occurence of a string by newline. Lets say I have this string test. I want to replace every occurence of this string by a newline. How can I do it in the shell

user34790
  • 2,020
  • 7
  • 30
  • 37

1 Answers1

1

If you use sed:

sed 's/abc/\n/' inupt.txt > output.txt

Suppose input.txt contains:

abc helo
a b c

You will end up with:

[newline]
  helo
a b c

Tested on Ubuntu 13.10 with sed 4.2, bash 4.2.

gongzhitaao
  • 6,566
  • 3
  • 36
  • 44
  • It replaces abc by n not newline – user34790 Dec 02 '13 at 23:36
  • @user34790 Are we using the same `bash` or the same `sed`? Or did you forget the backslash? or single quote? It works fine on my machine :) – gongzhitaao Dec 02 '13 at 23:37
  • @user34790 Might this [post](http://stackoverflow.com/questions/4247068/sed-command-failing-on-mac-but-works-on-linux) be of some help? This works on Ubuntu. I don't know about Mac. If it dosen't work, maybe just use some editor on Mac, do find and replace :) – gongzhitaao Dec 02 '13 at 23:43
  • 1
    If you are using `bash`, use `sed $'/abc/\n/' input.txt > output.txt` to guarantee that `sed` gets a newline, whether or not `sed` itself understands `\n` to be a newline. – chepner Dec 02 '13 at 23:46
  • @user34790 Another reason to forget about Mac if I want Linux. Thanks for your response on Mac :P – gongzhitaao Dec 02 '13 at 23:48
  • @chepner Are you sure that syntax works? – gongzhitaao Dec 02 '13 at 23:52
  • Oops. `sed` still needs the newline itself escaped, so it should be `sed $'/abc/\\\n/'`, so that `sed` sees `\` + `` as the replacement text. – chepner Dec 02 '13 at 23:56
  • @chepner Sorry, but it's still not working on my machine. – gongzhitaao Dec 02 '13 at 23:59