Hi Gurus,
I need to replace part of string in file, the string format is below: I can use ABCD to find string, then replace values after "=" sign
ABCD_XXX=value
ABCD_YYY=value
after replace
ABCD_XXX=new_value
ABCD_YYY=new_value
my OS is SunOS 5.10 Generic_150400-64 sun4v sparc sun4v
thanks in advance
Hi, you can use an input file with the new key value pairs
$> cat file1
ABCD_XXX=new_value1
ABCD_YYY=new_value2
$> cat file2
foo
ABCD_XXX=value1
ABCD_YYY=value2
bar=baz
Try:
awk 'NR==FNR{A[$1]=$2; next} $1 in A{$2=A[$1]}1' FS='=' OFS='=' file1 file2
Output:
foo
ABCD_XXX=new_value1
ABCD_YYY=new_value2
bar=baz
scrutinizer:
Hi, you can use an input file with the new key value pairs
$> cat file1
ABCD_XXX=new_value1
ABCD_YYY=new_value2
$> cat file2
foo
ABCD_XXX=value1
ABCD_YYY=value2
bar=baz
Try:
awk 'NR==FNR{A[$1]=$2; next} $1 in A{$2=A[$1]}1' FS='=' OFS='=' file1 file2
Output:
foo
ABCD_XXX=new_value1
ABCD_YYY=new_value2
bar=baz
thanks Scrutinizer. Sorry, I didn't give the sample properly. actually, there is only one value for all lines after equal. I updated my initial query. I tried to use awk command, I can use below command to print out correct result, but not sure how to replace it in file.
awk -F"=" '/ABCD/ {print $1"=value"}' file
You can redirect the output to a new file. If ok you can replace the old file with the new file:
nawk -F"=" '/ABCD/ {print $1"=value"}' file > newfile
1 Like
thanks Scrutinizer.
in the file, it has other contents which need to keep "as is". above command only print the match ones. how can I keep these file content as is.
for example:
old file:
aaaaaa
bbbbb
ABCD_XXX=value
ccccc
after replace:
aaaaaa
bbbbb
ABCD_XXX=new_value
ccccc
Hi Gurus,
I am able to use below command to get expected result. one more question:
I need to pass variable to this command, somehow it doesn't work.
awk -F"=" '!/ABCD/ {print $0}; /ABCD/ {print $1"=NEW_VALUE"}' file > new_file
I use below command, it throw out error.
awk -F"=" -v var="$new_value" '!/ABCD/ {print $0}; /ABCD/ {print $1"=${var}"}' file > new_file
green_k:
Hi Gurus,
I am able to use below command to get expected result. one more question:
I need to pass variable to this command, somehow it doesn't work.
awk -F"=" '!/ABCD/ {print $0}; /ABCD/ {print $1"=NEW_VALUE"}' file > new_file
I use below command, it throw out error.
awk -F"=" -v var="$new_value" '!/ABCD/ {print $0}; /ABCD/ {print $1"=${var}"}' file > new_file
simplified and fixed:
awk -F= -v var="$new_value" '/ABCD/ {$1= "=" var} 1' file > new_file
2 Likes
Not quite there $1 contains the variable name and is overwritten with "=" newvalue, try:
awk -F= -v var="$new_value" '/ABCD/ {$2 = var} 1' OFS== file > new_file
1 Like