user3211610
user3211610

Reputation: 11

append value to variable using sed - shell script

I am trying to search the file using the key and add 123 to the end of line. and other than the key "hello" I dont have values of hello. How can I achieve this sed or awk?

file contents

hello="80,30,255,64"

expected output

hello="80,30,255,64,123"

Upvotes: 1

Views: 1522

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

using awk

awk 'sub(/"$/,",123&")+1' infile

Test Results:

$ echo 'hello="80,30,255,64"' | awk 'sub(/"$/,",123&")+1'
hello="80,30,255,64,123"

sub(/"$/,",123&")+1 is incase if sub(), does not return non zero, then still print such line

I am trying to search the file using the key and add 123 to the end of line.

Can't find any key here, if you mean to say hello is your key then

awk '/^hello=/{ sub(/"$/,",123&") }1' infile > outfile

Explanation:

  • /^hello=/ - look for line starts with hello=

(^ indicates the beginning of the string.)

  • sub(/"$/,",123&") - substitute "$

( $ indicates the end of the string )

with comma, 123 and &

( special character & appears in replacement, it stands for the precise substring that was matched by regexp. )

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133428

Following awk code may help you in same.

awk -F"\"" '{$2=$2 ",123"} 1' OFS="\""  Input_file

Upvotes: 0

making_code
making_code

Reputation: 159

try the below sed expression:

sed 's/"$/,123"/' inputfile

It should give you:

hello="80,30,255,64,123"

Upvotes: 3

Related Questions