Results 1 to 3 of 3
  1. #1
    Join Date
    May 2010
    Posts
    2

    Unanswered: Trouble with editing script for multiple files

    Hey everybody, I have a script for making a string substitution in a file. I am trying to modify it in order to make the same modifcation to multiple files. here is what I have so far.

    Code:
    #!/bin/csh
    set p1="$1"
    shift
    set p2="$1"
    shift
    foreach x ($*)
    if ( { grep -w -c "$p1" $x } ) then
    mv $x $x.bak
    sed "s/$p1/$p2/g" $x.bak > $x
    else
    endif
    end
    An example would be
    ~/Unix/script/subst "hi guys" "hello everyone" myFile1.txt myFile2.txt

    which would make the same substitution in each file, and this should work for any number of files, with any substitution. the script works just fine for one file but I am haiving touble making it work for more than one currently.
    any help would be great. Thanks in advance!

  2. #2
    Join Date
    May 2010
    Posts
    2
    would just like to add everything my script is supposed to do wit hits parameters.

    1.the string to be replaced
    2.the string with which to replace it
    3.the name of the file in which to make the substitution
    4.performs the substitution and backup file creation when the target string occurs somewhere in the file, but leaves the file completely unchanged (and does not create the .bak file) if the string being replaced is nowhere in the file5. will apply a substitution to any number of files given on the command line

  3. #3
    Join Date
    Sep 2009
    Location
    Ontario
    Posts
    1,057
    Provided Answers: 1
    Just call your script multiple times:
    Code:
    $list=`ls [a-m]*.txt`     #or whatever
    for file in $list
    do
      subst "hi guys" "hello eveyone" $file 
    done
    Then simplify subst to:
    Code:
    #!/bin/csh
    set p1="$1"
    set p2="$2"
    
    if ( { grep -w -c "$p1" $3 } ) then
    mv $3 $3.bak
    sed "s/$p1/$p2/g" $3.bak > $3
    endif
    end
    Is there a reason you are still using csh?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •