cancel
Showing results for 
Search instead for 
Did you mean: 

Replace a word in a line

SOLVED
Go to solution
pgp_acc
Occasional Contributor

Replace a word in a line

Hi,

I have a problem in replacing a particular word in a file.
file format is like this:
1kkkkll
sjgkdsg
sggggggg
"ALL","sadf",,"55","Y",,"10","","7867"
"ALL","sadf",,"100","Y",,"100","","7868"
"ALL","sadf",,"100","N",,"100","","7868"
iewrowe

So on the 4th line,if the 5th word is "Y" then I want to change the 7th word.
I tried using perl,sed but problem it is changing the all the words equal to 100 or 10.

Thanks,
Priya
5 REPLIES
James R. Ferguson
Acclaimed Contributor

Re: Replace a word in a line

Hi Priya:

One way:

# perl -nle '@F=split /,/;if ($F[4]=~/Y/) {print join ",",@F[0..5],qq("999"),@F[7..@F-1]} else {print}' file

Regards!

...JRF...

pgp_acc
Occasional Contributor

Re: Replace a word in a line

Hi James,

Thanks for the prompt reply.
I tried with that its working:
But one problem when I'm trying to write into the same file is that its keeps the original line and duplicates the changed line as shown below:
perl -pi.bak -e '@F=split /,/; if ($F[4]=~/Y/){print join ",",@F[0..5],qq("999"),@F[7..@F-1]} else {print}' test
-- more test
1kkkkll
1kkkkll
sjgkdsg
sjgkdsg
sggggggg
sggggggg
"ALL","sadf",,"55","Y",,"999","","7867"
"ALL","sadf",,"55","Y",,"10","","7867"
"ALL","sadf",,"100","Y",,"999","","7868"
"ALL","sadf",,"100","Y",,"100","","7868"
"ALL","sadf",,"100","N",,"100","","7868"
"ALL","sadf",,"100","N",,"100","","7868"
iewrowe
iewrowe


Thanks,
Priya
James R. Ferguson
Acclaimed Contributor
Solution

Re: Replace a word in a line

Hi (again) Priya:

> But one problem when I'm trying to write into the same file is that its keeps the original line and duplicates the changed line as shown below...

...OK, so use this:

# perl -nli.bak -e '@F=split /,/;if ($F[4]=~/Y/) {print join ",",@F[0..5],qq("999"),@F[7..@F-1]} else {print}' file

...note the change of the '-p' for automatic printing of each record read to '-n' to suppress printing by default for each record read.

Regards!

...JRF...
pgp_acc
Occasional Contributor

Re: Replace a word in a line

Hi James,

It worked!!
Thanks :)

Priya
Dennis Handly
Acclaimed Contributor

Re: Replace a word in a line

You can use sed or awk, the latter is simpler:
awk -F, '
BEGIN { OFS = ","; NEWSTR = "\"XYZ\"" }
(NF != 9) {
print $0
next
}
$5 == "\"Y\"" {
print $1, $2, $3, $4, $5, $6, NEWSTR, $8, $9
} ' file > file.new

sed would need a RE:
sed 's/\([^,]*,[^,]*,[^,]*,[^,]*,"Y",[^,]*,\)\([^,]*\)/\1"XYZ"/' file > file.new