Flags inside sed command file

I have a sed file that replaces all occurrences of a string in a file with other string. I want to do it inline but without using -i from terminal What changes are to be made to the .sed file

#!/bin/sed
s/include/\#include/ 
4

2 Answers

Just use awk:

{ sub(/include/,"#include"); rec = rec $0 RS }
END{ printf "%s", rec > FILENAME }

or if you want to operate strictly on strings:

BEGIN{ old="include"; new="#include" }
s = index($0,old) {$0 = substr($0,1,s-1) new substr($0,s+length(old))
{ rec = rec $0 RS }
END{ printf "%s", rec > FILENAME }

which can be simplified to:

s = index($0,"include") {$0 = substr($0,1,s-1) "#" substr($0,s)
{ rec = rec $0 RS }
END{ printf "%s", rec > FILENAME }

in this particular case of just prepending # to a string.

I don't think it will work, because the -i and -f options can usually both have arguments, but you could be lucky.

The shebang line can contain one option group (aka cluster). You would need for it to contain -f (this is missing from your example) so the cluster could look like

#!/bin/sed -if

provided that your dialect doesn't require an argument to the -i option, and permits clustering like this in the first place (-if pro -i -f).

The obvious workaround is to change the script to a shell script; the -f option is no longer required because the script is not in a file.

#!/bin/sh
exec sed -i 's/include/\#include/' "$@"

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like