Results 1 to 2 of 2

Thread: I'm stuck in bash code...

  1. #1
    Join Date
    Nov 2013
    Beans
    1

    I'm stuck in bash code...

    Hi guys,
    Does anyone know's why my code doesn't run ? I want to replace the strtolower function from bash.

    Code:
    #!/bin/sh
      sed "y/strtolower/lower/" <run.php >run.php.new
    
    if [ -f run.php ]; then
      rm run.php && mv run.php.newrun.php
    
    fi
    Last edited by alex_deco20; November 16th, 2013 at 04:53 PM.

  2. #2
    Join Date
    Nov 2008
    Location
    Metro Boston
    Beans
    8,724
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: I'm stuck in bash code...

    The "y" command to sed does "transliteration" according to the sed manual page ("man sed"). If you want to replace all instances of strtolower with lower, then use "s" like this:

    Code:
    s/strtolower/lower/g
    Here's a little script I once wrote to replace all instances of string1 with string2 in all files matching filespec. I used it just yesterday to change all instances of POST to GET in a bunch of PHP files. You might find it helpful:

    Code:
    #!/bin/bash
    
    if [ "$1" = "" ]
    then
        echo "Syntax: replaceall 'string1' 'string2' 'filespec'"
        echo "Include the single quotes in your command"
        exit
    fi
    
    WD=$(pwd)
    NOW=`date +%s`
    TMP=~/.replaceall
    FILES=$(ls $3)
    mkdir -p $TMP/$NOW
    
    for i in $FILES;
    do
       TEST=$(grep "$1" $i)
       #echo "Checking $i; TEST=$TEST"  #uncomment for debugging
       if [ "$TEST" != "" ] 
       then
          echo "Replacing '$1' with '$2' in $i"
          # save backup copies
          cp $i $TMP/$NOW/$i.bak
          # do the replacement
          (sed "s_$1_$2_g" $i > $i.new) && (rm -f $i; mv $i.new $i)
       fi
    done
    
    cd $WD
    echo ""
    
    exit 0
    The "ls $3" command to get the filelist may not work correctly if you have files with embedded spaces. I never create such files so I don't encounter the problem. Also if the strings have underscore characters in them, you'll need to use a different delimiter in sed. The forward slash is the usual choice, as I used in the initial response above; the percent sign is often a good alternative.

    You'll find the backup copies in ~/.replaceall/[some number]; the largest number is the most recent save.
    Last edited by SeijiSensei; November 16th, 2013 at 05:54 PM.
    If you ask for help, please have the courtesy to check for responses and thank the people who helped you.

    Blog · Linode System Administration Guides · Android Apps for Ubuntu Users

Bookmarks

Posting Permissions

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