Replace a line in a text file
Dec. 9th, 2025 08:48 pmThis 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:
It is astonishingly simple:
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.
sed -i '4s/^.*$/new text/' file.txtIt 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.