Roland's homepage

My random knot in the Web

Inplace editing

This article describes how to edit files in-place programmatically. This has been part of my toolbox for a long time, so I thought I’d document it here.

Note

This requires a UNIX-like operating system. The necessary tools are generally not available on ms-windows.

Tools

We use sed to do the actual editing:

sed -i .bak -e 's/([Cc])/©/g' *.html

Note

the -i option on GNU sed is slightly different; it does not have a space between the -i option and its argument.

Combining sed with find is a flexible solution. Especially if you want to modify only some files in a tree:

find . -name '*.html' -exec sed -i '.bak' \
-e 's/([Cc])/©/g' {} \;

Examples

Updating templates; these are kept under revision control so generating backup files is not wanted, and we do not want to edit files in the revision control system directory:

find . -type f -not -path './.git/*' \
-exec sed -i '' -e 's/Time-stamp: <.*>/Time-stamp: <>/g' \
-e 's/Copyright © 20../Copyright © 2024/g' {} \;

Updating copyright date in source code:

find . -type f -not -path './.git/*' -name '*.py' \
-exec sed -i '' -e 's/Copyright © 20../Copyright © 2024/g' {} \;

Removing a line from a file:

find . -type f -not -path './.git/*' \
-exec sed -i '' -e '/. host: .*/d' {} \;

Edit references to TeXLive in configuration files:

cd ~/setup
find . -type f -not -path './.git/*' -not -name './*.jpg' \
-exec sed -i '' -e 's|texlive/2021|texlive/2022|g' {} \;

For comments, please send me an e-mail.


Related articles


←  Extracting glyphs from an OpenType file