2

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

MohamedAli
  • 313
  • 1
  • 5
  • 13

2 Answers2

4

Three possible ways to do it:

  1. awk -F: -v OFS=: '{for (i=1; i<=NF; i++) if ($i=="dog") $i="fox"} 1'
  2. perl -F: -lane 'print join ":" , map {$_ eq "dog" ? "fox" : $_} @F'
  3. 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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643