As Gordon commented, you can't edit a file simultaneously. But fear not; there are ways to edit it from multiple sources, or to do multiple independent edits.
Using sed's "replace all"
If all you're trying to do is replace one pattern multiple times, sed has a builtin flag ('g
') for it.
Input: Mary had a little lamb and a little cat
Edit: Change all occurrences of "a little
" with "a big
"
Run: sed 's/a little/a big/g'
Using multiple expressions
You can do multiple edits from the same sed. It can take an unlimited(ish) number of -e
arguments, each specifying an independent expression, which is run after all the previous expressions.
Input: Mary had a little lamb and a little cat
Edit: Change "lamb
" to "tarantula
" and "cat
" to "hamster
"
Run: sed -e 's/lamb/tarantula/' -e 's/cat/hamster/'
Using file locking
For cases where you are unable to form one sed expression to rule them all, you could run multiple sed
instances in different shells. This is the least recommended option because:
- it will still do the edits sequentially, as only one sed can safely run at a time
- the order of operations is not guaranteed, so if two expressions overlap, it will have undefined results (e.g. replace "little" with "big" and also replace "big" with "huge").
INOUT="/path/to/my/file"
{
flock --timeout 300 -x $auto_descriptor
sed -i 's/Mary/Jane/' "$INOUT"
} {auto_descriptor}>>"$INOUT"
(bash 4.1+ needed for the auto_descriptor part)