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?

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.

1
  • @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...) Jun 29 '18 at 10:17
7

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).

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
1
  • 1
    +1. If the appended text is not fixed I recommend to pass it as a variable to Awk to avoid escaping issues: awk -v suffix='xyz' 'BEGIN { FS = OFS = "=" }; $1 == "RELEASESTATUS" { $2 = $2 suffix; }; 1' Jun 29 '18 at 10:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.