1

I have tried a lot of commands, like this:

sed -i '' "s/$/<@string>/" txt.txt > txt2.txt

This makes txt2.txt empty, why?!?

sed 's/$/<@string>/' txt.txt > txt2.txt

This does absolutely nothing and tells me that the path <string> doesn't exist.

So what do i do, I'm using bsd sed because I'm on OS X.

1
  • -i '' is for in-place editing. txt.txt has been modified. sed has produced no output. Aug 22, 2014 at 11:58

2 Answers 2

3

The -i switch causes sed to edit the original file. That means there is no output and since there is no output, your redirection results in an empty file.

So, what you want is either

sed -i '' 's/$/<@string>/' txt.txt

which will change the original txt.txt. Or, just

 sed 's/$/<@string>/' txt.txt > txt2.txt
2
  • It makes no difference, are you sure that its for bsd and not GNU? It give me no error but the file isn't changed. Aug 22, 2014 at 12:09
  • @SurveySon the syntax is different for BSD (the -i needs a value which you are giving it with '') but the function is the same. If it's still not working, you probably have something strange in the input file or in whatever you are actually using instead of <@string>.
    – terdon
    Aug 22, 2014 at 14:23
0

The option -i in sed isn't quite compatible between Linux and Unix and it may not be available on other operating systems.

Secondly you can't use -i and IO-redirection (>) together, because it's excludes it-self. Using in-place editing already modifying the file.

So if you'd like to edit file in-place (into the same file), it's better to use ex:

ex +"%s/$/<@string>/g" -cwq foo.txt

To replace string and write to another file, try:

ex +"%s/$/<@string>/g" +"w another.txt" -cq! foo.txt

The command ex is equivalent to vi -e.

3
  • I solved this a year ago hehe, the problem was that the file was copied from an older computer with permissions problems. May 26, 2015 at 11:41
  • @DisplayName I'm glad you solved it, but since then your question generated almost 1k views, therefore I wanted to share alternative solution using ex/vi which is quite interesting, especially for cross-compatible scripting purposes.
    – kenorb
    May 26, 2015 at 12:10
  • Yeah, yeah that's good, was just saying. May 26, 2015 at 21:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .