Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


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

share|improve this question
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 0: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 1:16
up vote 2 down vote accepted

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
share|improve this answer
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 1: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 1: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 2:23

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!

share|improve this answer
great thanks for this – user36101 Mar 17 '10 at 4:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.