String search and replace in multiple files.

Hello.

I have five config files in /etc that I want to edit in one click for testing.

I would like to make a script like this :

#!/bin/bash
#
a_file="/etc/file_1"
src_str="src_string_1"
rpl_str="rpl_string_1"
calling_sed_or_awk_or_whatelse $a_file search_for_all $src_str replace_with $rpl_str
src_str="src_string_2"
rpl_str="rpl_string_2"
calling_sed_or_awk_or_whatelse $a_file search_for_all $src_str replace_with $rpl_str

# proceed to next file

a_file="/etc/file_2"
src_str="src_string_3"
rpl_str="rpl_string_3"
calling_sed_or_awk_or_whatelse $a_file search_for_all $src_str replace_with $rpl_str
src_str="src_string_4"
 rpl_str="rpl_string_4"
 calling_sed_or_awk_or_whatelse $a_file search_for_all $src_str replace_with $rpl_str

Thank you for helping

jcd
opensuse 11.3

How many files do you want to edit? 2 only?

Hello.

Five

/etc/samba/smb.conf
/etc/openldap/ldap.conf
/etc/openldap/slapd.conf
/etc/smbldap-tools/smbldap_bind.conf
/etc/smbldap-tools/smbldap.conf

And the purpose to do it in script is to minimize error as I have to make change in these files until I am satisfied.

jcd

Try this:

#!/usr/bin/perl
%h=(
  "/etc/samba/smb.conf"=>
  {
    "search_string_1"=>"replace_string_1",
    "search_string_2"=>"replace_string_2",
  },
  "/etc/openldap/ldap.conf"=>
  {
    "search_string_3"=>"replace_string_3",
    "search_string_4"=>"replace_string_4",
  },
  "/path/to/next/file"=>
  {
    "search_string_5"=>"replace_string_5",
    "search_string_6"=>"replace_string_6",
  },
);
for $i (keys %h){
local $/;
  open I, "$i";
  $_=<I>;
  for $j (keys %{$h{$i}}){
    s/$j/$h{$i}{$j}/g
  }
  close I;
  open I, ">$i";
  print I $_;
  close I;
}

Before running this code do a backup of those files. Add red sections of code with search and replace strings for all the files that you need.

1 Like

Ok I will try this afternoon.

Thank you very much.

By the way is it similar to this :

for F-NAME in /etc/samba/smb.conf /etc/openldap/ldap.conf /etc/openldap/slapd.conf /etc/smbldap-tools/smbldap_bind.conf /etc/smbldap-tools/smbldap.conf ; do 

# make new version ( keep source safe )
cp -f /backup/$F-NAME  $F-NAME

case $F-NAME in 
/etc/samba/smb.conf)
# should replace all occurences of ou=Computer by ou=Computer_id
cat $F-NAME | sed 's/"ou=Computer"/"ou=Computer_id"/g' 
# should replace all occurences of ou=User by ou=User_id
cat $F-NAME | sed 's/"ou=User"/"ou=User_id"/g' 
exit
;;
/etc/openldap/ldap.conf)
cat $F-NAME | sed 's/"rootpwd manager"/"rootpwd director"/g' 
exit
;;

..............
..............
..............
esac

done ;

---------- Post updated at 11:21 PM ---------- Previous update was at 12:44 PM ----------

Hello.

Great. That do the job.

Thank you very much.

:b:

JCD