miriam_e: from my drawing MoonGirl (Default)
[personal profile] miriam_e
This morning I was trying to write a small program to do various things, one of which was to modify a file. It needed to replace the text of line 4 of a file with some other text. I thought about it for a while, convinced that there must be a way to use sed to do it. After a while experimenting with various things I created this lovely fragment:

sed -i '4s/^.*$/new text/' file.txt

It is astonishingly simple:

sed ' '   is the stream text editor and its commands should be enclosed in single quotes so the shell doesn't get confused.

-i   means edit the file in place, overwriting the original file.

4   tells sed to apply the next command to line 4 in the input file.

s/ / /   means substitute what's between the first two slashes with what's between the second two slashes.

^.*$   means from the start of the line (^) any character (.) and any number of them (*) up to the end of the line ($).  So, everything on the line from the beginning of the line to the end of the line.

new text   is the text I replace the existing text on that line with.

file.txt   is the name of the file to be modified.

And it works like a charm!

I know this seems like a silly little thing, but I'm rapt I could get sed to do something like this so easily.

Profile

miriam_e: from my drawing MoonGirl (Default)
miriam_e

January 2026

S M T W T F S
    1 23
45678910
11121314151617
18192021222324
25262728293031

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 19th, 2026 12:55 am
Powered by Dreamwidth Studios