Bash shell: Replace a text block by another


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Bash shell: Replace a text block by another
# 1  
Old 01-07-2013
Bash shell: Replace a text block by another

Hello,
I'm an starter in Bash scripting. I would like to write a script in Bash shell that replaces a specific text block (a function) by another text block in a file:

for example in my file --> $HOME/myFile.js
replacing following function between other functions in the file:
Code:
function ABC()
{
  blablabla;
  blablabla;
}

by:
Code:
function ABC()
{
 another blablabla;
 another blablabla;
 another blablabla;
}

without doing any change on other text blocks (functions) in the file. Thanks in advance.
# 2  
Old 01-07-2013
You need to change this permanent in a one time event?
Or is it some that changes often?
If so, you can use a if then and select function on condition.
# 3  
Old 01-07-2013
I guess it's not that easy:
Code:
$ awk '{gsub("blablabla","another blabla")}1' file

We need some more info: will the new text block be supplied in another file? Is the text block to be replaced the entire function block or just parts thereof?
# 4  
Old 01-07-2013
in fact, I need that in a script that automates installation & configuration of a product.
since there in a bug in one of JavaScript files of the product, the content of one of fuctions should be replaced by something else.
I should install this product several times per month; therefore I'm preparing a script that does all necessary post-installation tasks with minmum manual actions.

---------- Post updated at 07:56 AM ---------- Previous update was at 07:52 AM ----------

new text block is supplied in another file; and will be replace the entire function ABC block.
# 5  
Old 01-07-2013
I'm sorry I can't test right now, but try sth like:
Code:
awk    'FNR==NR{Ar[++x]=$0;next}
        $0~Ar[1]{while ($0 != "}") getline; for (i=1;i<=x,i++) print Ar[i]}
        1
       ' rep_block orig_file

The function ABC... line in rep_block must be identical to the one in orig_file.
The proposal reads the entire replacement block into array Ar; then, tests every line read from orig_file against the first (line of rep_block =) element of Ar. If found, read and discard all the lines until the final } (may need to be escaped) is found; then, print out the Ar holding the replacement text.

Last edited by RudiC; 01-07-2013 at 05:32 AM..
# 6  
Old 01-07-2013
Hi.

A perl version for the specifics in this thread:
Code:
#!/usr/bin/env bash

# @(#) s1	Demonstrate structured text block replacement.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
edges() { local _f _n _l;: ${1?"edges: need file"}; _f=$1;_l=$(wc -l $_f);
  head -${_n:=3} $_f ; pe "--- ( $_l: lines total )" ; tail -$_n $_f ; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C perl

FILE=data1
pl " Input data file $FILE:"
cat $FILE

REP=data2
pl " Replacement text file $REP:"

pl " perl code:"
cat p1

pl " Results:"
./p1 $FILE

exit 0

producing:
Code:
% ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian GNU/Linux 5.0.8 (lenny) 
bash GNU bash 3.2.39
perl 5.10.0

-----
 Input data file data1:
any code in the file
function xyz()
{
}
function ABC()
{
  blablabla;
  blablabla;
}
function XYZ()
{
}
any other code in the file

-----
 Replacement text file data2:

-----
 perl code:
#!/usr/bin/env perl

# @(#) p1	Demonstrate structured block replacement.

use warnings;
use strict;

my ( $f, $code, $insert );
open( $f, "<", "data2" ) || die " Cannot open data2\n";
{

  # Best practices, p213 for a file.
  $code = do { local $/; <$f> };
}
close $f;

$insert = 0;
while (<>) {
  if ( /function ABC/ .. /^}/ ) {
    $insert = 1;
    next;
  }
  if ($insert) {
    $insert = 0;
    print $code;
  }

  print;
}

exit(0);

-----
 Results:
any code in the file
function xyz()
{
}
(new) function ABC()
{
 another blablabla;
 another blablabla;
 another blablabla;
}
function XYZ()
{
}
any other code in the file

Best wishes ... cheers, drl
# 7  
Old 01-10-2013
After some fiddling around with above proposal, this version will do the job:
Code:
$ awk  'FNR==NR{Ar[++x]=$0;next}
        $0==Ar[1] { while ($0 != "}") getline; getline; for (i=1;i<=x;i++) print Ar[i]}
        1
       ' file1 file
function XYZ()
{
  blablabla;
  blablabla;
}
function ABC()
{
 another blablabla;
 another blablabla;
 another blablabla;
}
function ABC1()
{
  blablabla;
  blablabla;
}

As awk appears to be a bit curt on the empty parentheses pair for a regex, we need to test for the exact identity in order not to lose the pair to distinguish that function from those with similar names. The second getline is needed to consume the last single }.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Bash script to replace text file from a lookup file

Hi. I need assistance with the replacing of text into a specific file via a bash script. My bash script, once run, currently provides a menu of computer names to choose.The script copies onto my system various files, depending what computer was selected in the menu.This is working OK. Now, I... (1 Reply)
Discussion started by: jonesn2000
1 Replies

2. Shell Programming and Scripting

Shell or perl script to replace XML text in bulk

Hi, I am looking for assistance over shell or perl (without XML twig module) which replace string in XML file under particular branch..example of code file sample.. Exact requirment : Replace "Su saldo es" in below file with "Your balance" but only in XML branch of Text id=98 and Text Id=12... (7 Replies)
Discussion started by: Ashu_099
7 Replies

3. Shell Programming and Scripting

How to replace word with multiline text using shell scripting.

Hi all I have data files which contain data as shown below: Line 5: FIDE INST_DESC: DIAM Co Ltd/Japan => MAID Co Ltd/Japan INST_NME: DIAM Co Ltd/Japan => MAID Co Ltd/Japan Line 6: FIDE INST_DESC: DIAM DL/Pimco US Bond Open Born in the USA => MAID DL/Pimco US Bond Open Born in the... (6 Replies)
Discussion started by: Ganesh_more
6 Replies

4. Shell Programming and Scripting

using sed/awk to replace a block of text in a file?

My apologies if this has been answered in a previous post. I've been doing a lot of searching, but I haven't been able to find what I was looking for. Specifically, I am wondering if I can utilize sed and/or awk to locate two strings in a file, and replace everything between those two strings... (12 Replies)
Discussion started by: kiddsupreme
12 Replies

5. Shell Programming and Scripting

Using shell to replace characters in a text file

Can I just say, this is such a frustrating and yet enormously rewarding field of study. I'm in the middle of configuring GeekTool (Uh oh, stupid n00b) and I really only have one question. I'm using Automator to grab a RSS feed, having GeekTool continually run that application every 10 minutes,... (7 Replies)
Discussion started by: SomeTechGuy
7 Replies

6. Shell Programming and Scripting

replace block of text with content of another file

Hello, file1: not to be changed not to be changed <start> old stuff old stuff old stuff <end> not to be changed not to be changed file2: new text new text desired output: (3 Replies)
Discussion started by: ripat
3 Replies

7. Homework & Coursework Questions

Help with bash shell to alter text file

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: My first question pertains to the adding a book section, I'm unsure which command or conditional statement I... (0 Replies)
Discussion started by: Vitrophyre
0 Replies

8. Shell Programming and Scripting

Replace text block in multiple files

I need to replace (delete) a text block in a bunch of files, its a html table, almost at the end of pages but the location varies. In Windows I used Filemonkey, but nothing like that in Unix? There is replace from mysql, but how does it deal with newlines? sed only works with single lines,... (6 Replies)
Discussion started by: eiland
6 Replies

9. Shell Programming and Scripting

Shell Script to replace text

I need a little help with a shell script. I want to be able to specify parameters so that the script searches multiple files (specified as parameters) and only modifies the file if it finds the string of text. For the files it doesn't find the string of text within, it should leave it alone. ... (4 Replies)
Discussion started by: joebaber
4 Replies

10. Shell Programming and Scripting

find, copy and replace text in bash or sh

here is my prob .. i have a very large text files and i need to locate specific lines, copy them and then replace a single word in the replaced text example find all lines that contain '/etc', copy the line immediately below (not at the end of the file) and then replace '/etc' with '/root'... (1 Reply)
Discussion started by: jmvbxx
1 Replies
Login or Register to Ask a Question