geo
geo

Reputation: 21

awk script replace 2nd occurrence of string inside double quotes

I'm having trouble making a script to replace a string that is inside double quotes. The files sections looks like this:

"regA~1"    :   "FF_NODE~94"
"regA~2"    :   "FF_NODE~105"
"regA~3"    :   "FF_NODE~116"
"regA~4"    :   "FF_NODE~127"
"regA~5"    :   "FF_NODE~138"
"regA~6"    :   "FF_NODE~149"
"regA~7"    :   "FF_NODE~154"
"regA~8"    :   "FF_NODE~155"
"regA~9"    :   "FF_NODE~156"
"regA~1"    :   "FF_NODE~95"
"regA~11"   :   "FF_NODE~96"

It works if I do

awk '/"regA~1"/{c++;if(c==2){sub("regA~1","regA~10");}}1' file > file_out

but when trying to make this a script where I pass a variable regA~1 and the value for c it doesn't work.

s="regA~1";
r="regA~10";
n=2;

awk -v search="$s" -v replace="$r" -v count=$n '/search/{c++;if(c==count){sub(search,replace);}}1' file > file_out

I also tried

awk -v search=$s -v replace=$r -v count=$n '/search/{c++;if(c==count){sub(search,replace);}}1' file > file_out

Upvotes: 2

Views: 962

Answers (2)

geo
geo

Reputation: 21

Thanks to Ed Morton for the tip. Here's the bash script in case anyone needs something like this. Not very sophisticated but it works for me.

#!/bin/bash
# Replaces a specific occurrence of a search string with a replace string
if [ $# -lt 4 ] ; then
echo -e "Wrong number of parameters."
echo -e "Usage:"
echo -e "repnthstr file search replace n"
echo -e "repnthstr fileext search replace n"
exit 1
fi

for file in $1
 do
 if [ -f $file -a -r $file ]; then
   awk -v search=$2 -v replace=$3 -v cnt=$4 '$0 ~ search{c++;if(c==cnt){sub(search,replace);}}1' "$file" > temp && mv temp "$file"
 else
  echo "Error: Cannot read $file"
 fi
done

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203532

The syntax you need to match an RE that's stored as a string in a variable is

$0 ~ var

not

/var/

Upvotes: 1

Related Questions