Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

search exact string

Status
Not open for further replies.

Shellmaster

Programmer
Joined
Feb 25, 2011
Messages
2
Location
DE
Hello,

i have a small problem searching an exact String.

i want to make a substitution via sub("old","new") or gsub("old","new"). But i only want to the word "old" to be replaced.

Example :

old
older
gold

after using my awk-script i always get

new
newer
gnew

but what i want is

new
older
gold

can someone help me? I think its just a problem of the right reg. exp. or search string. i tried a lot but cant find it :(

thanks a lot
 
Hi

[tt]gawk[/tt] can do it :
Code:
awk '{gsub(/[highlight]\y[/highlight]old[highlight]\y[/highlight]/,"new")}1' /input/file
But I am afraid, other implementations can not handle the [tt]\y[/tt] metacharacter. Which is usually [tt]\b[/tt] in regular expressions.

Off-topic alternatives :
Code:
perl -pe 's/[highlight]\b[/highlight]old[highlight]\b[/highlight]/new/g' /input/file

sed 's/[highlight]\b[/highlight]old[highlight]\b[/highlight]/new/g' /input/file

Feherke.
 
Hey feherke,

thank yo very much it works fine to this point :)

now i want to put a LOOP variable into the regex like

for(i=1;i<=5,i++){

gsub(/\yoldi\y/,"new"i)

}

but it doesnt work, it always makes the i part of the String like "i" and not the reference to the number (1-5) of the variable.


greetings
 
Hi

You can not include variable names in the regular expression literal.

However in AWK you can use strings in place of regular expression literals :
Code:
[b]gsub[/b][teal]([/teal][green][i]"[/i][/green][lime][i]\\[/i][/lime][green][i]yold"[/i][/green]i[green][i]"[/i][/green][lime][i]\\[/i][/lime][green][i]y"[/i][/green][teal],[/teal][green][i]"new"[/i][/green][teal])[/teal]
Just pay attention to the metacharacters' backslashes ( \ ) as they must be escaped in string literals.


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top