Programming

How to use sed to replace only the first occurrence in a file

25 September 2026 · 6 min read

How to use sed to replace only the first occurrence in a file

Mastering the command-line can feel like wielding a digital scalpel, capable of precise and powerful edits. One such tool in the command-line arsenal is sed, the stream editor. While sed offers a plethora of text manipulation options, a common challenge is replacing only the first occurrence of a string within a file. This seemingly simple task can be tricky, but with the right approach, you can harness sed’s power for efficient and accurate file modifications. This guide will explore various methods to achieve this, providing clear explanations and practical examples to help you become proficient in using sed for targeted replacements.

Using the s Command with the q Flag

The most straightforward method to replace only the first occurrence with sed involves combining the substitution command (s) with the quit (q) flag. This tells sed to exit immediately after the first successful substitution.

The basic syntax is:

sed 's/original/replacement/q' filename

Here, “original” is the string you want to replace, “replacement” is the new string, and “filename” is the file you’re modifying. This command modifies the file in-place. If you prefer to create a new file with the changes, use the -i flag with an extension:

sed -i'.bak' 's/original/replacement/q' filename

This creates a backup of the original file with a “.bak” extension.

Addressing Multiple Occurrences on the Same Line

The previous method works perfectly for replacing the first occurrence in the entire file. But what if a line contains multiple instances of the string, and you only want to replace the first one on that specific line? For this, we leverage the number flag within the s command.

The syntax becomes:

sed 's/original/replacement/1' filename

The 1 following the last / specifies that only the first occurrence on each line should be replaced.

Leveraging Addresses for Targeted Replacements

sed allows you to specify addresses, which define the lines where the command should be executed. This offers granular control over your replacements. You can specify a single line number, a range of lines, or even use regular expressions to match specific lines.

For example, to replace the first occurrence only on line 5:

sed '5s/original/replacement/' filename

Or, to replace the first occurrence within lines 2 through 10:

sed '2,10s/original/replacement/q' filename

Note how we combine addressing with the q flag to ensure only the very first occurrence within the specified range is replaced.

Using Variables for Flexibility

For more complex scenarios, you can use shell variables to store the strings you want to replace. This makes your scripts more reusable and easier to maintain.

original="old_string" replacement="new_string" sed "s/$original/$replacement/q" filename

Remember to enclose the sed command in double quotes when using variables.

  • Always test your sed commands on a copy of your file first to avoid unintended changes.
  • Regular expressions can be used within the s command for more complex pattern matching.

Here’s a step-by-step example of using variables and the -i flag:

  1. Create a test file:
echo "This is a test line." > test.txt echo "This is another test line." >> test.txt
  1. Define your variables:
original="test" replacement="example"
  1. Run the sed command:
sed -i'.bak' "s/$original/$replacement/q" test.txt

Now, test.txt will contain “This is an example line.” and “This is another test line.”, while test.txt.bak will retain the original content. This illustrates the power of sed for precise, single-occurrence replacements.

For complex replacements involving special characters, remember to escape them appropriately within your sed command using backslashes. For example, to replace a period (.), use \..

Learn more about regular expressions.

External Resources:

[Infographic Placeholder: Visual guide to using sed for replacements]

FAQ

Q: What if I need to replace the nth occurrence in a file?

A: While sed doesn’t directly support replacing the nth occurrence across multiple lines, you can achieve this by combining sed with other command-line tools like awk or by using more advanced scripting techniques.

Effectively replacing the first occurrence of a string in a file using sed allows for precise and streamlined file manipulation. By understanding the different methods outlined in this guide – using the q flag, the number flag, addresses, and shell variables – you can tailor your sed commands to suit various scenarios. Practice these techniques to enhance your command-line proficiency and optimize your text processing workflows. Explore more advanced sed features, like regular expressions and scripting, to unlock even greater control over your text editing tasks. Dive deeper into the world of command-line tools and discover the efficiency and precision they offer.

Question & Answer :
I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file.

How do I get sed to replace just the first occurrence of a string in a file rather than replacing every occurrence?

If I use

sed s/#include/#include "newfile.h"\n#include/ 

it replaces all #includes.

Alternative suggestions to achieve the same thing are also welcome.

A sed script that will only replace the first occurrence of “Apple” by “Banana”

Example

Input: Output: Apple Banana Apple Apple Orange Orange Apple Apple 

This is the simple script: Editor’s note: works with GNU sed only.

sed '0,/Apple/{s/Apple/Banana/}' input_filename 

The first two parameters 0 and /Apple/ are the range specifier. The s/Apple/Banana/ is what is executed within that range. So in this case “within the range of the beginning (0) up to the first instance of Apple, replace Apple with Banana. Only the first Apple will be replaced.

Background: In traditional sed the range specifier is also “begin here” and “end here” (inclusive). However the lowest “begin” is the first line (line 1), and if the “end here” is a regex, then it is only attempted to match against on the next line after “begin”, so the earliest possible end is line 2. So since range is inclusive, smallest possible range is “2 lines” and smallest starting range is both lines 1 and 2 (i.e. if there’s an occurrence on line 1, occurrences on line 2 will also be changed, not desired in this case). GNU sed adds its own extension of allowing specifying start as the “pseudo” line 0 so that the end of the range can be line 1, allowing it a range of “only the first line” if the regex matches the first line.

Or a simplified version (an empty RE like // means to re-use the one specified before it, so this is equivalent):

sed '0,/Apple/{s//Banana/}' input_filename 

And the curly braces are optional for the s command, so this is also equivalent:

sed '0,/Apple/s//Banana/' input_filename 

All of these work on GNU sed only.

You can also install GNU sed on OS X using homebrew brew install gnu-sed.