1

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?

0

1 Answer 1

4

awk can help:

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

or sed

sed -i '/^PRODUCT5/s/$type$/$type2/' input
5
  • It works like a charm :)
    – Paolo
    Dec 19, 2011 at 11:53
  • Thanks a lot man!!One question: why you have type $type$??
    – Paolo
    Dec 19, 2011 at 11:53
  • @Paolo: to match $type at end of line, so that executing twice would not perform the substitution again.
    – enzotib
    Dec 19, 2011 at 11:55
  • 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, 2011 at 12:39
  • @Paolo: the awk solution do not work with spaces, but the sed one should work. Remove the -i option to see output on stdout without modifying the input file. In any case, it is always a good habit to show (a piece of) the real input, and not a pseudo-input.
    – enzotib
    Dec 19, 2011 at 13:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .