Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a file like this:

PRODUCT: $name | YEAR: $year | TYPE: $type
PRODUCT2: $name2 | YEAR: $year | TYPE: $type2
PRODUCT3: $name3 | YEAR: $year | TYPE: $type
PRODUCT4: $name4 | YEAR: $year | TYPE: $type3
PRODUCT5: $name5 | YEAR: $year | TYPE: $type
PRODUCT6: $name6 | YEAR: $year | TYPE: $type
PRODUCT7: $name7 | YEAR: $year | TYPE: $type3
PRODUCT8: $name8 | YEAR: $year | TYPE: $type2


And i want to change a specifiy field.
For example i want to change the type of PRODUCT5 from $type to $type2 but i don't want to replace the whole line, only the field i'd like to change!
Is this possible?

share|improve this question
add comment

1 Answer 1

awk can help:

awk '{ if ($1 == "PRODUCT5:") $8 = "$type2"; print }' input
mv output input

or sed

sed -i '/^PRODUCT5/s/$type$/$type2/' input
share|improve this answer
    
It works like a charm :) –  Paolo Dec 19 '11 at 11:53
    
Thanks a lot man!!One question: why you have type $type$?? –  Paolo Dec 19 '11 at 11:53
    
@Paolo: to match $type at end of line, so that executing twice would not perform the substitution again. –  enzotib Dec 19 '11 at 11:55
    
Aaaah ok :) thanks again! –  Paolo Dec 19 '11 at 11:57
    
and if $type has space into the name?? for example: name type2 ?? how can i say to awk that $8 is "name type" and not only "name"?? –  Paolo Dec 19 '11 at 12:39
show 1 more comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.