Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help editing files in place with sed

I am trying to add a file in place with sed and I keep getting this error message

sed: 1: "test.txt": undefined label 'est.txt'

This is the command I am using

Desktop > sed -i 's/White/Black/' test.txt

I am not sure what I am doing incorrect here.... Any help will be really appreciated! Thanks in advance!

like image 515
Eldan Shkolnikov Avatar asked Nov 14 '14 21:11

Eldan Shkolnikov


People also ask

Does sed change the original file?

By default sed does not overwrite the original file; it writes to stdout (hence the result can be redirected using the shell operator > as you showed).

Is sed an interactive editor?

Introduction. The sed command, short for stream editor, performs editing operations on text coming from standard input or a file. sed edits line-by-line and in a non-interactive way. This means that you make all of the editing decisions as you are calling the command, and sed executes the directions automatically.

How do you replace a variable in a file using sed?

How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.


1 Answers

Some versions of sed require an argument for -i. Try:

sed -i.bak  's/White/Black/' test.txt

Or (OSX/BSD only),

sed -i ''  's/White/Black/' test.txt

As you know, -i tells sed to edit in place. The argument the extension to use for the back-up of the original file. The argument is the empty string, your sed will likely not keep a back-up file.

GNU sed does not require an argument for -i. BSD sed (Mac OSX) does.

Details

Consider the command:

sed -i 's/White/Black/' test.txt

If your sed requires an argument to -i, then it would believe that s/White/Black/ was that argument. Consequently, it believes that the next argument, test.txt, is the sed command that it should execute. This would be interpreted as the "test" command t with the intention of jumping to the label est.txt if the test is true. No such label has been defined. Hence the error message:

sed: 1: "test.txt": undefined label 'est.txt'

Alternative

ThatOtherGuy reports that the following will run without error on all platforms:

sed -i -e 's/White/Black/' test.txt

ThatOtherGuy notes that the behavior of this line is, however, platform-dependent. With BSD sed, it creates a back-up file with a -e extension. With GNU sed, no back-up is created.

like image 87
John1024 Avatar answered Sep 28 '22 06:09

John1024