5

I have a text file keyvalue.txt with contents:

one=abc
two=def
three=ghi
four=jkl
five=mno
six=pqr

Now, I want to append xyz to value of three that will become

three=ghixyz

The resulting file contents should be:

one=abc
two=def
three=ghixyz
four=jkl
five=mno
six=pqr

Is there any way to do this in shell scripting?

3 Answers3

9

There are several ways; e.g. with sed:

sed -i 's/^RELEASESTATUS=.*/&xyz/' keyvalue.txt

This looks for lines starting with RELEASESTATUS=, matching the full line (thanks to .*), and replaces those lines with the contents of the line (&) followed by xyz.

Stephen Kitt
  • 434,908
  • @Jathavedas you’re welcome. Please take the [tour], and if one of the answers works for you, accept it using the big checkmark. (Kusulananda’s answer is better than mine...) – Stephen Kitt Jun 29 '18 at 10:17
6

Similar to Stephen's answer, but slightly different in the way it's executed:

sed -i '/^RELEASESTATUS=/s/$/xyz/' keyvalue.txt

Instead of replacing the entire line with a copy of itself with some text added to the end, this first locates the correct line (the line that has RELEASESTATUS= at the very start) and then substitutes in the required text at the end of that line.

This uses the fact that the general form of the substitute command (s) in sed is

start,end s/pattern/replacement/flags

where start and end gives the range of lines that the command should be applied to, given as a start and end address (and "address" may be a line number or regular expression, or an offset). When using a single address, the command is applied to that line only (or to the single lines matching a particular regular expression).

Kusalananda
  • 333,661
2

You can also try with awk:

awk 'BEGIN { FS = OFS = "=" }; $1 == "RELEASESTATUS" { $2 = $2"xyz"; }; 1' keyvalue.txt

And if you have GNU awk 4.1.0 or later you can do it inplace:

gawk -i inplace -v INPLACE_SUFFIX=.bak 'BEGIN { FS = OFS = "=" }; $1 == "RELEASESTATUS" { $2 = $2"xyz"; }; 1' keyvalue.txt
taliezin
  • 9,275