sed: replace first instance only with string containing bash variable

sed replace first occurrence after match
awk replace first occurrence
bash replace string in file
sed replace first occurrence in string
sed only first line
sed replace first occurrence of character in line
sed replace only first occurrence in each line
sed regex first occurrence

This is a bit of a follow-on from How to use sed to replace only the first occurrence in a file? but with a more targeted ask. Given a file

Peach: data/file1.txt
Apple: data/file2.txt
Pear: data/file3.txt
Apple: data/file4.txt

The goal is to replace only the first line containing Apple with a new line containing a fixed string (Banana) followed by a bash variable. In the new output, line 2 is now:

Banana: newdata/data.txt

Here is the most recent attempt...

sed -i -E "0,|(Apple).*|{s|(Apple:).*|Banana: "$BananaVariable"/data.txt|}" filename

However, this produces the error:

sed: -e expression #1, char 3: unexpected  `,'

I think I need the double quotes around $BananaVariable to escape so that it can insert the actual string rather than "BananaVariable", but I think those double quotes are causing the problem. (OS is CentOS 7, sed is GNU version)

From man sed:

       Match lines matching the regular expression regexp.

       Match  lines  matching the regular expression regexp.  The c may
       be any character.

So in your original command replace the first two bars | with slash / (equivalently, replace the first | with \|):

sed -i -E "0,/(Apple).*/{s|(Apple:).*|Banana: $BananaVariable/data.txt|}" filename

You can also shorten the command:

sed -i -E "0,/^Apple/s|.*|Banana: $BananaVariable/data.txt|" filename


Peach: data/file1.txt
Banana: newdata/data.txt
Pear: data/file3.txt
Apple: data/file4.txt

Want to substitute only first occurence with sed, This is a range that starts with line 1 and ends with the first occurrence of claudio . both read the whole file into a single string, then the search will only replace the first one. of do block p # print the pattern space b # go to the end of the script, continue with next line :x # the To select any line that contains claudio , use: 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.

It is easier with awk:

awk -v v="$var" 'BEGIN{FS=OFS=": "}
!p && $1 == "Apple"{$1="Banana"; $2=v; p=1} 1' file

Peach: data/file1.txt
Banana: newdata/data.txt
Pear: data/file3.txt
Apple: data/file4.txt

How to Use sed to Find and Replace String in Files, With sed you can search, find and replace, insert, and delete strings and lines. If you omit the g flag only the first instance of the search string in each line 123 Foo linux foo linux /bin/bash Ubuntu foobar 456 Sometimes you want to recursively search directories for files containing a string and replace  By default, sed reads the file line by line and changes only the first occurrence of the SEARCH_REGEX on a line. When the replacement flag is provided, all occurrences will be replaced. When the replacement flag is provided, all occurrences will be replaced.

This might work for you (GNU sed):

sed -i -e '0,/Apple/!b;//cBanana: '"$BananaVariable"'/data.txt' file

If a line is not between the front of the file until a line containing Apple print as normal. Otherwise change the line containing Apple to the required string using a variable.

Match the First Occurrence Only with SED, In other words, we will match the first occurrence only with sed on the Linux command line. Now we could extend the regular expression to include the server If we remove the p command at the end of the string and replace the -n PERL Scripting in Linux · Learn Shell Scripting with BASH · Master  sed -i 's+regex+new-text+g' file.txt. The above replace all occurrences of characters in word1 in the pattern space with the corresponding characters from word2. Examples that use sed to find and replace. Let us create a text file called hello.txt as follows: $ cat hello.txt. The is a test file created by nixCrft for demo purpose.

How to Find and Replace a String in File Using the sed Command in , Sed command is mostly used to replace the text in a file. cat sed-test.txt 1 Unix unix unix 23 2 linux Linux 34 3 linuxunix UnixLinux linux /bin/bash CentOS Linux OS Linux is free This only changes the first instance of the pattern on each line. 10) How to Find and Replace a String that Contains the Delimiter Character. You can run that in the prompt, or put it into a file and run the file. Replace in place. -i for “in place”, it means that no copy of the file will be created. $ sed -i 's/vermin/pony/g' metamorphosis.txt. Using variables as replace and search values. Variables can be used just as well, only they need to be interpolated and the first sed

Sed - An Introduction and Tutorial, If you want to change a pathname that contains a slash - say Sed will match the first string, and make it as greedy as possible. If you tell it to change a word, it will only change the first occurrence of the word on On many systems, sed can have only one comment, and it must be the first line of the script. Bash String Manipulation Examples – Length, Substring, Find and Replace. In bash shell, when you use a dollar sign followed by a variable name, shell expands the variable with its value. This feature of shell is called parameter expansion.

Sed Command in Linux/Unix with examples, Today we will talk about a very useful tool for string manipulation called sed or The above result shows the first occurrence in each line is only replaced. The p flag prints each line contains a pattern match, you can use the -n option to Suppose that you want to search for bash shell and replace it with csh shell in the​  sed or awk command to replace a string pattern with another string based on position of this string here is what i want to achieve consider a file contains below contents. the file size is large about 60mb cat dump.sql INSERT INTO `table1` (`id`, `action`, `date`, `descrip`, `lastModified`) VALUES (1,'Change','2011-05-05 00:00:00','Account

  • You should drop the double quotes around $BananaVariable as it renders the variable effectively unquoted.
  • @Sergio Your first suggestion works correctly and involves the fewest changes to the current code -- thanks! Your second suggestion is the most economic solution proposed (so far).