Replace a line in a text file
Tuesday, 9 December 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.
Additional: I should have spent some time reading about sed's commands. I just now half-remembered that sed had a command to replace a line of text, so I checked my documentation, and yes, it does. So the command to replace line 4 of a file could be as simple as this:
This is the same as the earlier example, except the
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.
Additional: I should have spent some time reading about sed's commands. I just now half-remembered that sed had a command to replace a line of text, so I checked my documentation, and yes, it does. So the command to replace line 4 of a file could be as simple as this:
sed -i '4c new text' file.txtThis is the same as the earlier example, except the
c command tells sed to change the line to what follows. The space following the c command is not really necessary (sed ignores it), but it makes the command much easier to read. If you want the line to start with a space then precede the space with a backslash (\) so sed won't ignore it.