Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace entire paragraph with another from linux command line

The problem I have is pretty straightforward (or so it seems). All I want to do is replace a paragraph of text (it's a header comment) with another paragraph. This will need to happen across a diverse number of files in a directory hierarchy (source code tree).

The paragraph to be replaced must be matched in it's entirety as there are similar text blocks in existence.

e.g.

To Replace

// ----------
// header
// comment
// to be replaced
// ----------

With

// **********
// some replacement
// text
// that could have any
// format
// **********

I have looked at using sed and from what I can tell the most number of lines that it can work on is 2 (with the N command).

My question is: what is the way to do this from the linux command line?

EDIT:

Solution obtained: Best solution was Ikegami's, fully command line and best fit for what I wanted to do.

My final solution required some tweaking; the input data contained a lot of special characters as did the replace data. To deal with this the data needs to be pre processed to insert appropriate \n's and escape characters. The end product is a shell script that takes 3 arguments; File containing text to search for, File containing text to replace with and a folder to recursively parse for files with .cc and .h extension. It's fairly easy to customise from here.

SCRIPT:

#!/bin/bash
if [ -z $1 ]; then
    echo 'First parameter is a path to a file that contains the excerpt to be replaced, this must be supplied'
  exit 1
fi

if [ -z $2 ]; then
    echo 'Second parameter is a path to a file contaiing the text to replace with, this must be supplied'
  exit 1
fi

if [ -z $3 ]; then
    echo 'Third parameter is the path to the folder to recursively parse and replace in'
  exit 1
fi

sed 's!\([]()|\*\$\/&[]\)!\\\1!g' $1 > temp.out
sed ':a;N;$!ba;s/\n/\\n/g' temp.out > final.out
searchString=`cat final.out`
sed 's!\([]|\[]\)!\\\1!g' $2 > replace.out
replaceString=`cat replace.out`

find $3 -regex ".*\.\(cc\|h\)" -execdir perl -i -0777pe "s{$searchString}{$replaceString}" {} +
like image 515
radman Avatar asked Oct 31 '11 04:10

radman


1 Answers

find -name '*.pm' -exec perl -i~ -0777pe'
    s{// ----------\n// header\n// comment\n// to be replaced\n// ----------\n}
     {// **********\n// some replacement\n// text\n// that could have any\n// format\n// **********\n};
' {} +
like image 51
ikegami Avatar answered Nov 15 '22 06:11

ikegami