Find and replace text in files with xonsh

133 Views Asked by At

How would one replace text in all files within a given directory (recursively) while in the xonsh shell?

For example, how would I rewrite the below bash command:

find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +
2

There are 2 best solutions below

1
On BEST ANSWER

I might try this:

for fpath in pg`*baz*`:
    if not fpath.is_file():
        continue
    fpath.write_text(fpath.read_text().replace('foo', 'bar'))
0
On

Just add the quotes to tell xonsh that {} and + are the arguments:

find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' '{}' '+'

The complete example of testing your command in xonsh:

echo 'foo foo' > some_baz_file
find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' '{}' '+'
cat some_baz_file
# bar bar

Another way is to use the xonsh macro command and just run bash line as is:

bash -c! find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +

To simplify this approach there is xontrib-sh extension that allows just add the ! sign before the command:

! find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +