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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK/KSH and special characters during string sub

Status
Not open for further replies.

mirasta

Programmer
Feb 23, 2010
2
CY
Hi

My problem is related to escaping special characters like the dollar sign in variables, while doing substitutions.
I've tried perl sub, awk sub, sed substitution with no success.


Explanation:
A CSV file contains lines, with 2 values per line separated by comma.
The first value is used as a token and the second as the value of the token as you can see below in the array.

Program flow is:
1) take token and new value from CSV file using AWK
2) grep the token in the file which needs to be modified
3) If token found then compare the existing value with the new value from the CSV and substitute them if needed (This is the problem coz values begin with $)
4) If not found then just insert the token and its value from the CSV file into the target file.


Getting Values from csv (works):
Code:
token=`awk -F"," '{print $1}' input.txt`;
newvalue=`awk -F"," '{print $2}' input.txt`;
set -A token_array $token
set -A newvalue_array $newvalue

Inserting new line in target file (works):
Code:
 new_Line="${token_array[i]}=${newvalue_array[i]}";
        awk 'BEGIN { print "'"$new_Line"'" >> "'"$file"'" }';

Finding the token and changing its value if old_value and new_value aren't...no idea how to do it:

showing perl here as an example.
Code:
perl -pi -w -e \"s|${old_value}|${newvalue_array[i]}|g\" $file"`;

The problem happens when $old_value evaluates to $blahblah
If it does that, then I need to escape the $ somehow, because I need to treat it as a string for String Substitution and not as a variable.


Any advise on if this is possible with AWK would be great.
I know the whole thing looks like a mess and there would be 1k ways of doing it better...but I'm just starting :))



 
It makes little sense to use awk to add a new line to a file, when you could just use:

Code:
echo "$new_Line" >> $file

Something like this may work for you:

Code:
awk -v old="${old_value}" -v new="${newvalue_array[i]}" '{gsub(old,new,$0);print}' $file > $file.new

Assigning values to awk variables using -v helps prevent descending into quote-hell when trying to interpolate them into the actual awk script.

Annihilannic.
 
Hi Annihilannic,

Thanks for the response.

Out of the box it doesn't seem to replace the values from old to new, but I ll play it with some more and post back.

Thanks for the -v tip :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top