I have a file which has : separated data like
cat:dog:lion cat:mouse:tiger
and I am trying to replace dog with anther value like fox for example using bash. I need the changes to take place inside the file without changing the other data
I have a file which has : separated data like
cat:dog:lion cat:mouse:tiger
and I am trying to replace dog with anther value like fox for example using bash. I need the changes to take place inside the file without changing the other data
Three possible ways to do it:
awk -F: -v OFS=: '{for (i=1; i<=NF; i++) if ($i=="dog") $i="fox"} 1'
perl -F: -lane 'print join ":" , map {$_ eq "dog" ? "fox" : $_} @F'
sed -r 's/^|$/:/g; s/:dog:/:fox:/g; s/^:|:$//g;'
With sed and perl, use -i
to edit the file in-place.
With awk: awk ... > tmpfile && mv tmpfile orig_file
You can use sed inline:
sed -i.bak -r 's/(^|:)dog(:|$)/\1fox\2/g' file
OR on OSX:
sed -i.bak -E 's/(^|:)dog(:|$)/\1fox\2/g' file
Becuase of -i
flag changes will be saved in the file itself.