awk help - delimited file

Hi,

I have a delimited file with 10 fields. I have to replace a character in field 1 and field 5. It is possible to do using awk where i can read a row at a time field by field and if the field value is 1 or 5 then i will replace the character.

But this operation is cumbersome since the file size is huge and if the columns are more than 100.

Is there an option where i can do the operation on the field without looping through every field ie Directly act on the field 1 and field 5 without reading all the other field values as in my previous case.

please give a sample of input and output expected

what is your delimiter ?
which character do you want to replace, and by which one ?

Sample data :

Record 1 : aca|bbb|ccc|ddd|eee|aaa|bb7
Record 2 : aca|xyz|xyz|ddd|eee|aaa|bb7

I want to replace character a in field 1 with & and character b in field 7 with #

Output:

Record 1 : &c&|bbb|ccc|ddd|eee|aaa|##7
Record 2 : &c&|xyz|xyz|ddd|eee|aaa|##7
awk -F\| '{gsub("a","&",$1);gsub("b","#",$7)}1' file > out.file

Hi,

It is replacing the 7th field but not the first field..
This is the output i am getting

$ cat test1 
aca bbb ccc ddd eee aaa bb7
aca xyz xyz ddd eee aaa bb7

$ cat test1 | nawk -F\| '{gsub("a","&",$1);gsub("b","#",$7)}1'
aca bbb ccc ddd eee aaa ##7
aca xyz xyz ddd eee aaa ##7
$ awk -F\| '{gsub("a","\\&",$1);gsub("b","#",$7)}1' file
Record 1 : &c& bbb ccc ddd eee aaa ##7
Record 2 : &c& xyz xyz ddd eee aaa ##7

Thanks.

Is there anyway I can achieve it without using the "\\". The reason is, I am going to do it for a set of characters in a set of fields. So i am going to generate the command based on the inputs, if I were to add the "\\" it becomes difficult to identify for which characters i need to prefix with \\.

You can do something like:

awk 'BEGIN{
  printf "Enter the character: "
  getline value < "-"
}
value=="&"{value="\\"value}
{
  gsub("x",value)
}
1' file

Or you can externalize the variables like this. The ampersand will need to be escaped with two slashes if it in the replacement variable

awk -F'|' '{gsub(a,anew,$1);gsub(b,bnew,$NF)}1' OFS="|" a=a b=b anew="\\&" bnew="#" infile

The ^ , $ , (, ), { } need to be escaped with 4 \\\\ if they need to be replaced... and the \ needs 7 escapes:
bnew="\\\\\\\\"