Need help understanding ex command

Will someone please help me understand why the '%s\n' is required in the following ex command sequence?

printf '%s\n' '%s/oldPattern/newPattern/g' 'x' | ex file.ext

I understand the '%s/oldPattern/newPattern/g' and 'x'.

The testing that I've done shows that I need the '%s\n' for ex to do the edit to file.ext.

N.B. I would do this with sed -i '%s/oldPattern/newPattern/g' file.ext on a contemporary Linux system but I'm trying to replicate that type of behavior on an older Solaris 10 system with stock tools.

Thank you for explaining -> helping me understand why '%s\n' is needed.

Edit: Added the % -- that I had in my test but missed in my post -- before the s/oldPattern/newPattern/g per @munkeHoller's observation.

That's the format for the printf
Each %s takes one following argument. The \n is a newline. When there are more arguments than %s then the format is re-applied on them.
For example
printf "%s %s\n" a b c d e f
In your case it puts each argument on a new line:
printf "%s\n" "line 1" "line 2"

1 Like

printf command accepts one or more arguments and displays them as instructed by the FORMAT string(s) (at least the first argument, can have multiple FORMAT string as mentioned by @MadeInGermany)
Without '%s\n', the output produced (and piped to ex) by printf would be s/oldPattern/newPattern/g (the second argument would not even be considered), and with '%s' (without \n) it would produce s/oldPattern/newPattern/gx from two arguments concatenated, whereas you most likely need

s/oldPattern/newPattern/g
x

in separate lines, for ex to work correctly.

1 Like

:man_facepalming:

Thank you @MadeInGermany that makes perfect sense. I was conflating printf's formatting string as an ex command.

Thank you.

I knew that there had to be something I was missing. Hence why I asked for help.

Thank you @Matt-Kita.

@DrScriptt , my two kopeks: this only changes the last line of the input file ! , ex is perfectly adequate to make the required change, don't fix it if its working :sunglasses:

cat file.ext 
oldPattern , NO CHANGE
oldPattern , NO CHANGE
oldPattern , NO CHANGE
oldPattern  , this will be changed

printf '%s\n' 's/oldPattern/newPattern/g' 'x' | ex file.ext

cat file.ext 
oldPattern , NO CHANGE
oldPattern , NO CHANGE
oldPattern , NO CHANGE
newPattern  , this will be changed

Good catch @munkeHoller. I believe you are correct. However ....

I realized after your helpful comment that I failed to include a % in the s/oldPattern/newPattern/g which causes ed / ex / vi / vim to apply the regular expression to all lines in the buffer.

I'll edit the post to amend that.