Reputation: 97
I have a file called names.xml
That looks like the below:
NAME="Stacey" SURNAME="Ford"
blah blah blah
NAME="Stacey" SURNAME="Ford"
blah blah blah
I need to find all occurrences of NAME=" and with the "" quotes I need to replace the name with another value.
So the output needs to look like this:
NAME="Jack" SURNAME="Ford"
blah blah blah
NAME="Jack" SURNAME="Ford"
blah blah blah
I am using: sed 's/NAME=".*"/NAME="Jack"/g' names.xml
But this is the result it gives me:
NAME="Jack"
blah blah blah
NAME="Jack"
blah blah blah
It is looking at everything up until the last " on SURNAME.
Your time and assistance is greatly appreciated.
Upvotes: 0
Views: 118
Reputation: 41460
Here is an awk
version:
awk -F\" -vOFS=\" '$1~/NAME=/ {$2="Jack"}1' file
NAME="Jack" SURNAME="Ford"
blah blah blah
NAME="Jack" SURNAME="Ford"
blah blah blah
Use "
as field separator. If field 1
contains NAME=
replace filed 2
with Jack
and print it.
Upvotes: 2
Reputation: 174806
You need to use a negated character class [^"]*
which matches any character but not of "
zero or more times. .*
in your regex is greedy by default, it eats all the characters upto the last "
double quotes. So that only it matches Stacey
and upto the last Ford
. And also you must need to add a word boundary \b
before the NAME
, so that it won't match the string NAME
in SURNAME
. \b
matches between a word character and a non-word character.
sed 's/\bNAME="[^"]*"/NAME="Jack"/g' names.xml
Upvotes: 5