Editing a File in Place

Problem

You want to edit an existing file without affecting the inode or permissions.

Solution

This is trickier than it sounds because many tools you might ordinarily use, such as sed, will write to a new file (thus changing the inode) even if they go out of their way to preserve other attributes.

The obvious solution is to simply edit the file and make your updates. However, we admit that that may be of limited use in a scripting situation. Or is it?

In Prepending Data to a File, you saw that sed writes a brand new file one way or another; however, there is an ancestor of sed that doesn’t do that. It’s called, anticlimactically, ed, and it is just as ubiquitous as its other famous descendant, vi. And interestingly, ed is scriptable. So here is our “prepend a header” example again, this time using ed:

# Show inode
$ ls -i data_file
306189 data_file

# Use printf "%b" to avoid issues with 'echo -e' or not.
$ printf "%b" '1i\nHeader Line1\nHeader Line2\n.\nw\nq\n' | ed -s data_file
1 foo

$ cat data_file
Header Line1
Header Line2
1 foo
2 bar
3 baz

# Verify inode has NOT changed
$ ls -i data_file
306189 data_file

Discussion

Of course you can store an ed script in a file, just as you can with sed. In this case, it might be useful to see what that file looks like, to explain the mechanics of the ed script:

$ cat ed_script
1i
Header Line1
Header Line2

.
w
q

$ ed -s data_file < ed_script
1 foo

$ cat data_file
Header Line1
Header Line2
1 foo
2 bar
3 baz

The 1i in the ed script ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.