Bruen Link 🚀

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

April 5, 2025

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

Mastering the bid-formation tin awareness similar wielding a integer scalpel, susceptible of exact and almighty edits. 1 specified implement successful the bid-formation arsenal is sed, the watercourse application. Piece sed provides a plethora of matter manipulation choices, a communal situation is changing lone the archetypal incidence of a drawstring inside a record. This seemingly elemental project tin beryllium difficult, however with the correct attack, you tin harness sed’s powerfulness for businesslike and close record modifications. This usher volition research assorted strategies to accomplish this, offering broad explanations and applicable examples to aid you go proficient successful utilizing sed for focused replacements.

Utilizing the s Bid with the q Emblem

The about easy technique to regenerate lone the archetypal incidence with sed entails combining the substitution bid (s) with the discontinue (q) emblem. This tells sed to exit instantly last the archetypal palmy substitution.

The basal syntax is:

sed 's/first/substitute/q' filename

Present, “first” is the drawstring you privation to regenerate, “substitute” is the fresh drawstring, and “filename” is the record you’re modifying. This bid modifies the record successful-spot. If you like to make a fresh record with the modifications, usage the -i emblem with an delay:

sed -i'.bak' 's/first/alternative/q' filename

This creates a backup of the first record with a “.bak” delay.

Addressing Aggregate Occurrences connected the Aforesaid Formation

The former technique plant absolutely for changing the archetypal incidence successful the full record. However what if a formation accommodates aggregate cases of the drawstring, and you lone privation to regenerate the archetypal 1 connected that circumstantial formation? For this, we leverage the figure emblem inside the s bid.

The syntax turns into:

sed 's/first/alternative/1' filename

The 1 pursuing the past / specifies that lone the archetypal prevalence connected all formation ought to beryllium changed.

Leveraging Addresses for Focused Replacements

sed permits you to specify addresses, which specify the strains wherever the bid ought to beryllium executed. This affords granular power complete your replacements. You tin specify a azygous formation figure, a scope of traces, oregon equal usage daily expressions to lucifer circumstantial strains.

For illustration, to regenerate the archetypal prevalence lone connected formation 5:

sed '5s/first/alternative/' filename

Oregon, to regenerate the archetypal prevalence inside strains 2 done 10:

sed '2,10s/first/substitute/q' filename

Line however we harvester addressing with the q emblem to guarantee lone the precise archetypal incidence inside the specified scope is changed.

Utilizing Variables for Flexibility

For much analyzable situations, you tin usage ammunition variables to shop the strings you privation to regenerate. This makes your scripts much reusable and simpler to keep.

first="old_string" alternative="new_string" sed "s/$first/$substitute/q" filename

Retrieve to enclose the sed bid successful treble quotes once utilizing variables.

  • Ever trial your sed instructions connected a transcript of your record archetypal to debar unintended adjustments.
  • Daily expressions tin beryllium utilized inside the s bid for much analyzable form matching.

Present’s a measure-by-measure illustration of utilizing variables and the -i emblem:

  1. Make a trial record:
echo "This is a trial formation." > trial.txt echo "This is different trial formation." >> trial.txt
  1. Specify your variables:
first="trial" substitute="illustration"
  1. Tally the sed bid:
sed -i'.bak' "s/$first/$alternative/q" trial.txt

Present, trial.txt volition incorporate “This is an illustration formation.” and “This is different trial formation.”, piece trial.txt.bak volition hold the first contented. This illustrates the powerfulness of sed for exact, azygous-prevalence replacements.

For analyzable replacements involving particular characters, retrieve to flight them appropriately inside your sed bid utilizing backslashes. For illustration, to regenerate a play (.), usage \..

Larn much astir daily expressions.

Outer Sources:

[Infographic Placeholder: Ocular usher to utilizing sed for replacements]

FAQ

Q: What if I demand to regenerate the nth incidence successful a record?

A: Piece sed doesn’t straight activity changing the nth prevalence crossed aggregate strains, you tin accomplish this by combining sed with another bid-formation instruments similar awk oregon by utilizing much precocious scripting methods.

Efficaciously changing the archetypal prevalence of a drawstring successful a record utilizing sed permits for exact and streamlined record manipulation. By knowing the antithetic strategies outlined successful this usher – utilizing the q emblem, the figure emblem, addresses, and ammunition variables – you tin tailor your sed instructions to lawsuit assorted eventualities. Pattern these methods to heighten your bid-formation proficiency and optimize your matter processing workflows. Research much precocious sed options, similar daily expressions and scripting, to unlock equal larger power complete your matter modifying duties. Dive deeper into the planet of bid-formation instruments and detect the ratio and precision they message.

Question & Answer :
I would similar to replace a ample figure of C++ origin records-data with an other see directive earlier immoderate present #contains. For this kind of project, I usually usage a tiny bash book with sed to re-compose the record.

However bash I acquire sed to regenerate conscionable the archetypal prevalence of a drawstring successful a record instead than changing all prevalence?

If I usage

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

it replaces each #consists of.

Alternate options to accomplish the aforesaid happening are besides invited.

A sed book that volition lone regenerate the archetypal incidence of “Pome” by “Banana”

Illustration

Enter: Output: Pome Banana Pome Pome Orangish Orangish Pome Pome 

This is the elemental book: Application’s line: plant with GNU sed lone.

sed 'zero,/Pome/{s/Pome/Banana/}' input_filename 

The archetypal 2 parameters zero and /Pome/ are the scope specifier. The s/Pome/Banana/ is what is executed inside that scope. Truthful successful this lawsuit “inside the scope of the opening (zero) ahead to the archetypal case of Pome, regenerate Pome with Banana. Lone the archetypal Pome volition beryllium changed.

Inheritance: Successful conventional sed the scope specifier is besides “statesman present” and “extremity present” (inclusive). Nevertheless the lowest “statesman” is the archetypal formation (formation 1), and if the “extremity present” is a regex, past it is lone tried to lucifer towards connected the adjacent formation last “statesman”, truthful the earliest imaginable extremity is formation 2. Truthful since scope is inclusive, smallest imaginable scope is “2 strains” and smallest beginning scope is some traces 1 and 2 (i.e. if location’s an incidence connected formation 1, occurrences connected formation 2 volition besides beryllium modified, not desired successful this lawsuit). GNU sed provides its ain delay of permitting specifying commencement arsenic the “pseudo” formation zero truthful that the extremity of the scope tin beryllium formation 1, permitting it a scope of “lone the archetypal formation” if the regex matches the archetypal formation.

Oregon a simplified interpretation (an bare RE similar // means to re-usage the 1 specified earlier it, truthful this is equal):

sed 'zero,/Pome/{s//Banana/}' input_filename 

And the curly braces are optionally available for the s bid, truthful this is besides equal:

sed 'zero,/Pome/s//Banana/' input_filename 

Each of these activity connected GNU sed lone.

You tin besides instal GNU sed connected OS X utilizing homebrew brew instal gnu-sed.