How to use xargs with ed?

211 views Asked by At

I want to batch replace strings recursively inside a folder, and I have settled with using Perl. I would like to see if there is a solution which requires less dependency and work across platforms.

For listing files, I can use anything from ls to find to ag, rg. Lemme demonstrate my problem with ls.

ls | xargs -I '{}' ed -s {} <<< $'='

I will get this:

Is a directory newline appended =: No such file or directory

As the pipe is used for passing filenames to xargs, and streams (here-string) seems not working (How can heredocs be used with xargs?). I wonder if it is possible to use xargs with ed.

My concern is cross platform and in fact that command will be put inside package.json for npm run global_replace. We are wondering if there are solutions other than introducing gulp-replace and gulp just for this task.

2

There are 2 answers

2
Sunny Pun On BEST ANSWER

After some investigation, using herestring is not completely impossible:

find ... | xargs -0 -I{} sh -c 'ed -s "$1" <<< '"$',s/foo/bar/g\nw'" -- {}

And in package.json, I have to escape each ", so now we can run npm run replace. The exit code will be status 1 and it does not look good although it works.

Many thanks to @Benjamin.W for his help in the comments!

1
Vinod Kumar On

Try this solution:

find . -name "*" | xargs sed -i 's/regex/replacestring/g'