5

How can I use search and replace to change the contents of a file.

I need to be able to change the 'all to none' and/or 'none to all' without having to manually do it every time for hundreds of lines.

below is a sample text file with lines numbers on the right. I know how to open and close the file for writing already.

Lines

1 define_filter absolute_minimal_filter ------- all
2 define_filter atma_basic_filter -------- ----- none
3 define_filter atma_communication_filter -- all
4 define_filter atma_health_filter ------------- none
5 define_filter atma_misc_filter --------------- all
6 define_filter atma_performance_filter ---- none
7 define_filter atma_supplemental_filter ---- none

user36101
  • 53
  • 3
  • Why Perl? Do you just need a method to search and replace, or do you actually need to use Perl for some reason? Have you consider simply opening your document with a text editor? – Zoredache Feb 26 '10 at 00:35
  • Perl can certainly do this and it's quite trivial but as Zoredache indicates, it's even simpler to do with the search and replace in a text editor. Now to the point - Why did you ask such a question here? – John Gardeniers Feb 26 '10 at 01:16

2 Answers2

3

Just out of interest, the Perl solution is pretty similar to the sed one:

perl -pi.bak -e 's/all$/none/ || s/none$/all/' input_file

EDIT: I missed the "||" first time. As separate statements, the second would undo the first. D'oh!

Martin
  • 516
  • 2
  • 4
  • 14
2

With a well-chosen string in place of "temp" (in two places):

sed 's/all/temp/g;s/none/all/g; s/temp/none/g' input_file > output_file

or without a temp string if "all" and "none" never appear on the same line and always end the line:

sed 's/all$/none/;t;s/none$/all/' input_file > output_file
Dennis Williamson
  • 62,149
  • 16
  • 116
  • 151
  • i know how to search and replace simply using sed but i need to be able to change each line independently – user36101 Feb 26 '10 at 01:22
  • @user36101: I read your question to mean that you wanted to toggle all the lines. What do you mean independently? Use a text editor or use a selector in `sed`: `sed '/atma_misc_filter/ s/...` (as above). You can use the `-i` switch to make `sed` make the changes in place. – Dennis Williamson Feb 26 '10 at 01:46
  • using the first version with the temp string may change a real temp in the data, so the 2nd version is more preferable – user37841 Mar 17 '10 at 02:23