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 Answers 3

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...) Commented Jun 29, 2018 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).

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
2
  • 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' Commented Jun 29, 2018 at 10:03
  • Beware using gawk -i inplace like that introduces a security vulnerability unless you modify $AWKPATH not to include . or make sure you run that command from within a working directory where nobody could create a file called inplace or inplace.awk. Commented Jun 24, 2023 at 21:17

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.