Dec. 9th, 2025

miriam_e: from my drawing MoonGirl (Default)
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

December 2025

S M T W T F S
 123456
7 8 910 111213
1415 1617181920
21222324252627
28293031   

Style Credit

Expand Cut Tags

No cut tags
Page generated Dec. 24th, 2025 12:56 pm
Powered by Dreamwidth Studios