My Board
How to Replace the nth Occurrence of a Pattern in a Line Using a sed Command - Printable Version

+- My Board (https://ellohost.com/forum)
+-- Forum: Tutoriel EN (https://ellohost.com/forum/forumdisplay.php?fid=8)
+--- Forum: Others (https://ellohost.com/forum/forumdisplay.php?fid=20)
+--- Thread: How to Replace the nth Occurrence of a Pattern in a Line Using a sed Command (/showthread.php?tid=714)



How to Replace the nth Occurrence of a Pattern in a Line Using a sed Command - aaron - 09-06-2023


    How to Replace the nth Occurrence of a Pattern in a Line Using a sed Command
   

How to Replace the nth Occurrence of a Pattern in a Line Using a sed Command


   
   

Insert the corresponding character, either a slash ( / ) or a vertical bar ( | ), and substitute the hash ( # ) symbol with the desired number to replace the nth occurrence of a pattern in a line. Here's the basic syntax:


   
sed ‘s/old_string/new_string/#’ samplefile.txt

   

For example, to replace the first occurrence of the word "music" with "song" in a line inside the playlist.txt file, enter:


   
sed ‘s/music/song/1’ playlist.txt