regex - how to replace everything except string of interest -
file.txt
fruits:banana,apple,grape,limon,orange,tomate, fruits:apple,limon, fruits:banana,grape,limon, fruits:orange,tomate,grape, fruits:banana, fruits:apple, fruits:banana,apple,
i need replace different "banana" fruit, , output this:
fruits:banana,fruit,fruit,fruit,fruit,fruit, fruits:fruit,fruit, fruits:banana,fruit,fruit, fruits:fruit,fruit,fruit, fruits:banana, fruits:fruit, fruits:fruit,apple,
i tried using awk, can replace fields of specific strings.
example replace strings "apple" fruit2, or strings "apple" fruit2 , strings "tomate"or "orange" fruit3
awk -f":" '{ gsub(/apple/,"fruit2",$2); print }' ofs="," file.tx
or
awk -f":" '{ gsub(/apple/,"fruit2",$2);;gsub(/tomate|orange/,"fruit3",$2); print }' ofs="," file.txt |sed "s/./:/7" fruits:banana,fruit2,grape,limon,fruit3,fruit3, fruits:fruit2,limon, fruits:banana,grape,limon, fruits:fruit3,fruit3,grape, fruits:banana, fruits:fruit2, fruits:banana,fruit2
but need replace different string, ex: fruit4
how generate output this?
fruits:fruit4,fruit2,fruit4,fruit4,fruit3,fruit3, fruits:fruit2,fruit4, fruits:fruit4,fruit4,fruit4, fruits:fruit3,fruit3,fruit4, fruits:fruit4, fruits:fruit2, fruits:fruit4,fruit2
this awk should work:
awk -f, -v ofs=, '{ (i=1; i<=nf; i++) if ($i !~ /(^|:)banana$/) sub(/[^:]+$/, "fruit", $i) } 1' file
output:
fruits:banana,fruit,fruit,fruit,fruit,fruit, fruits:fruit,fruit, fruits:banana,fruit,fruit, fruits:fruit,fruit,fruit, fruits:banana, fruits:fruit, fruits:banana,fruit,
Comments
Post a Comment