Skip to content
Latchkey

xargs With sed: Bulk Edit Files in CI

xargs feeds a list of files into sed -i so one substitution edits every file in place.

Sweeping a rename or replacement across a repo is a classic xargs job: list the files, then run sed -i on all of them in batches.

What it does

A file source (find or grep -l) produces names, and xargs hands them to sed -i, which edits each file in place. xargs batches the files into efficient sed invocations. The safe form uses NUL separation and -r so spaces and empty results do not break the edit.

Common usage

Terminal
# rename a symbol across the tree
grep -rlZ 'getUser' src | xargs -0 -r sed -i 's/getUser/fetchUser/g'
# only TypeScript files
find src -name '*.ts' -print0 | xargs -0 -r sed -i 's/v1/v2/g'

Options

FlagWhat it does
sed -iEdit files in place
xargs -0Read NUL-terminated names (with -print0 or grep -Z)
xargs -rDo nothing if no files were listed
xargs -n <n>Limit files per sed run if needed
sed -i (GNU vs BSD)BSD sed -i requires a backup-suffix argument

In CI

Pin your runner OS for sed: GNU sed -i takes no argument, while BSD/macOS sed -i needs an explicit suffix like "sed -i '' ...". A codemod that works on a Linux runner can fail on a macOS runner over this one difference. Keep -0 and -r in the pipe so odd filenames and empty results are safe.

Common errors in CI

On macOS, "sed -i 's/a/b/'" errors with "sed: 1: ...: invalid command code" because BSD sed read the script as the backup suffix; use "sed -i ''". Without -0, a path with spaces yields "sed: can't read <fragment>: No such file or directory". Without -r, an empty list makes sed hang reading stdin.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →