Sponsored Content
Top Forums Shell Programming and Scripting Script to find & replace a multiple lines string across multiple php files and subdirectories Post 302604196 by agama on Saturday 3rd of March 2012 03:14:00 PM
Old 03-03-2012
Is the block of code the only block that starts <?php and finishes ?>? I suspect that maybe there are other blocks that start and end this way, but on the off chance that this will be the only block like this, then this sed should work:

Code:
sed '/<?php/,/?>/d'  "$file-" >"$file"

It deletes all lines between the starting line with "<?php" and the ending "?>" line as it reads the file. The updated file is written to $file.

If you can use this sed, just replace it in the earlier example.

If there are more than one php blocks of code, then you'll need to find a unique string inside the block that you want to delete. Change the one line in the script below that has "/enter your nickname/" to contain the unique string from the block of code and it should find and delete the lines containing the string.

Code:
#!/usr/bin/env ksh

cd /directory/path/where/you/want/to/start
find . -name "*.php" | while read file
do
    echo "munging: $file"             # nice to see progress as it works
    mv "$file" "$file-"      # back it up
    awk '     # read the file and delete the block of php code
    /<?php/ { drop = idx = 0; snarf = 1; }  # start of a block; start buffering

    /?>/ {                  # end of a block
        if( ! drop )        # magic string not found -- show this block
        {
            for( i = 0; i < idx; i++ )
                printf( "%s\n", buffer[i] );
            printf( "%s\n", $0 );
        }

        snarf = 0;          # turn off buffering
        next;
    }

    ### change the string between the slants to be something unique to the block you wish to delete. 
    /enter your nickname/ { drop = 1; }    # magic string found, drop if we are in a php block

    snarf {                 # if buffering, hold the record until end of block reached.
        buffer[idx++] = $0;
        next;
    }

    { print; }              # not buffering, just print the record.
    '  "$file-" >"$file"
    if (( $? > 0 ))            # handle failure by putting the file back in place
    then
        echo "edit of $file failed" >&2
        mv "$file-" "$file"             # restore original
    else
        rm "$file-"               # worked, delete backup 
    fi
done



Hope this helps get you going.

Last edited by agama; 03-04-2012 at 01:44 PM.. Reason: corrected comment that introduced a bug
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Find and Replace in multiple files (Shell script)

hi guys, Suppose you have 100 files in a folder and you want to replace all occurances of a word say "ABCD" in those files with "DCBA", how would you do it ??? jatin (13 Replies)
Discussion started by: jatins_s
13 Replies

2. UNIX for Dummies Questions & Answers

Find and replace a string in multiple files

I used the following script cd pathname for y in `ls *`; do sed "s/ABCD/DCBA/g" $y > temp; mv temp $y; done and it worked fine for finding and replacing strings with names etc. in all files of the given path. I'm trying to replace a string which consists of path (location of file) ... (2 Replies)
Discussion started by: pharos467
2 Replies

3. Shell Programming and Scripting

replace multiple lines in multiple files

i have to search a string and replace with multiple lines. example Input echo 'sample text' echo 'college days' output echo 'sample text' echo 'information on students' echo 'emp number' echo 'holidays' i have to search a word college and replace the multiple lines i have... (1 Reply)
Discussion started by: unihp1
1 Replies

4. Shell Programming and Scripting

shell script to find and replace string in multiple files

I used the following script cd pathname for y in `ls *`; do sed "s/ABCD/DCBA/g" $y > temp; mv temp $y; done and it worked fine for finding and replacing strings with names etc. in all files of the given path. I'm trying to replace a string which consists of path (location of file) ... (11 Replies)
Discussion started by: pharos467
11 Replies

5. Shell Programming and Scripting

Find & Replace string in multiple files & folders using perl

find . -type f -name "*.sql" -print|xargs perl -i -pe 's/pattern/replaced/g' this is simple logic to find and replace in multiple files & folders Hope this helps. Thanks Zaheer (0 Replies)
Discussion started by: Zaheer.mic
0 Replies

6. Shell Programming and Scripting

Single/Multiple Line with Special characters - Find & Replace in Unix Script

Hi, I am creating a script to do a find and replace single/multiple lines in a file with any number of lines. I have written a logic in a script that reads a reference file say "findrep" and populates two variables $FIND and $REPLACE print $FIND gives Hi How r $u Rahul() Note:... (0 Replies)
Discussion started by: r_sarnayak
0 Replies

7. Shell Programming and Scripting

how can i find number of lines in files & subdirectories

how can i find number of lines in files & subdirectories ? (3 Replies)
Discussion started by: pcbuilder
3 Replies

8. Shell Programming and Scripting

replace (sed?) a string in file with multiple lines (string) from variable

Can someone tell me how I can do this? e.g: a=$(echo -e wert trewt ertert ertert ertert erttert erterte rterter tertertert ert) How do i replace the STRING with $a? I try this: sed -i 's/STRING/'"$a"'/g' filename.ext but this don' t work (2 Replies)
Discussion started by: jforce
2 Replies

9. Shell Programming and Scripting

Search & Replace: Multiple Strings / Multiple Files

I have a list of files all over a file system e.g. /home/1/foo/bar.x /www/sites/moose/foo.txtI'm looking for strings in these files and want to replace each occurrence with a replacement string, e.g. if I find: '#@!^\&@ in any of the files I want to replace it with: 655#@11, etc. There... (2 Replies)
Discussion started by: spacegoose
2 Replies

10. Shell Programming and Scripting

Replace a string with multiple lines

Hello Guys, I need to replace a string with multiple lines. For eg:- ABC,DEF,GHI,JKL,MNO,PQR,STU need to convert the above as below:- ABC,DEF, GHI1 GHI2 GHI3, JKL,MNO, PQR1 PQR2 PQR3, STU i have tried using code as:- (2 Replies)
Discussion started by: jassi10781
2 Replies
HEADER(3)								 1								 HEADER(3)

header - Send a raw HTTP header

SYNOPSIS
void header (string $string, [bool $replace = true], [int $http_response_code]) DESCRIPTION
header(3) is used to send a raw HTTP header. See the HTTP/1.1 specification for more information on HTTP headers. Remember that header(3) must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(3), or require(3), functions, or another file access function, and have spaces or empty lines that are output before header(3) is called. The same problem exists when using a single PHP/HTML file. <html> <?php /* This will give an error. Note the output * above, which is before the header() call */ header('Location: http://www.example.com/'); exit; ?> PARAMETERS
o $string - The header string. There are two special-case header calls. The first is a header that starts with the string " HTTP/" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the ErrorDocument directive), you may want to make sure that your script generates the proper status code. <?php header("HTTP/1.0 404 Not Found"); ?> REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set. <?php header("Location: http://www.example.com/"); /* Redirect browser */ /* Make sure that code below does not get executed when we redirect. */ exit; ?> o $replace - The optional $replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in FALSE as the second argument you can force multiple headers of the same type. For example: <?php header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: NTLM', false); ?> o $http_response_code - Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the $string is not empty. RETURN VALUES
No value is returned. CHANGELOG
+--------+---------------------------------------------------+ |Version | | | | | | | Description | | | | +--------+---------------------------------------------------+ | 5.1.2 | | | | | | | This function now prevents more than one header | | | to be sent at once as a protection against header | | | injection attacks. | | | | +--------+---------------------------------------------------+ EXAMPLES
Example #1 Download dialog If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the Content-Dispo- sition header to supply a recommended filename and force the browser to display the save dialog. <?php // We'll be outputting a PDF header('Content-Type: application/pdf'); // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="downloaded.pdf"'); // The PDF source is in original.pdf readfile('original.pdf'); ?> Example #2 Caching directives PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with: <?php header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past ?> Note You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached. Additionally, session_cache_limiter(3) and the session.cache_limiter configuration setting can be used to automatically gen- erate the correct caching-related headers when sessions are being used. NOTES
Note Headers will only be accessible and output when a SAPI that supports them is in use. Note You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start(3) and ob_end_flush(3) in your script, or setting the out- put_buffering configuration directive on in your php.ini or server configuration files. Note The HTTP status header line will always be the first sent to the client, regardless of the actual header(3) call being the first or not. The status may be overridden by calling header(3) with a new status line at any time unless the HTTP headers have already been sent. Note There is a bug in Microsoft Internet Explorer 4.01 that prevents this from working. There is no workaround. There is also a bug in Microsoft Internet Explorer 5.5 that interferes with this, which can be resolved by upgrading to Service Pack 2 or later. Note If safe mode is enabled the uid of the script is added to the realm part of the WWW-Authenticate header if you set this header (used for HTTP Authentication). Note HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname(3) to make an absolute URI from a relative one yourself: <?php /* Redirect to a different page in the current directory that was requested */ $host = $_SERVER['HTTP_HOST']; $uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\'); $extra = 'mypage.php'; header("Location: http://$host$uri/$extra"); exit; ?> Note Session ID is not passed with Location header even if session.use_trans_sid is enabled. It must by passed manually using SID con- stant. SEE ALSO
headers_sent(3), setcookie(3), http_response_code(3), The section on HTTP authentication. PHP Documentation Group HEADER(3)
All times are GMT -4. The time now is 12:50 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy