Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
is there a way to replace the nth field in a
variable in awk?
e.g. given a variable in awk:
Var="1,23,3,4"
i need to replace the 3rd field(assuming delimiter=comma) to "789" and print the output. so my output should look like "1,23,789,4".i cannot use the traditional match-and-replace commands(they replace based on the value, not the position) as the value of the nth field is not fixed. the other option is getline. but i didn't find any construct to redirect the contents of a variable to getline.
any help is appreciated.
Tushar.

Here's one way, but it's not very nice. Split the variable up into an array and change the required element in the array - 3 in this case. If I were you, I'd consider creating an awk function to perform this:
echo " "|awk '
{
f=3 # field to change
var="1,23,4,4"
nvar=""
rv=789
nf=split(var,a,",")for(i=1; i<=nf; i++)
{
if(i == f)
a[i]=rvif(i == 1)
{
nvar=a[i]
continue
}nvar=nvar","a[i]
}
var=nvar
print var
} '

thanks nails. i know this solution. basically it will work. but for big files, it will take too long. atleast, something is better than nothing. :)
for better performance, i was hoping for something like pointing the input-stream to this variable. then i could simply say:
"$3=789; print". the reasoning is it will apply the default rules(field-separation, etc) directly on the contents of the variable. but i don't think awk supports it.

VAR="1,23,3,4"
echo $VAR | awk -F"," ' { printf("%s,%s,%s,%s,%s,%s\n",$1,$2,"789",$4,$5,$6)} ' | sed 's/,*$//'Luke Chi

![]() |
grep scripts
|
Is it possible ?
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |