473,387 Members | 1,464 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

How to search and replace string using perl?

Hi,

I had a few questions regarding searching for a string and replacing it using perl scripts. I have 100's of files written in Unix shell scripts and I need to edit them all. Its like
Expand|Select|Wrap|Line Numbers
  1. function1()
  2.          variable=xxx
  3. }
  4.  
  5. function 2()
  6. {
  7.          variable='aaa bbb ccc ddd'
  8. }
  9.  
I have to search exactly for function 2 and only replace the variable in function 2. I have to append a new value ggg to the variable only in function 2.

Everytime I try doing this with the perl one liner 's/searchtext/replacetext/g', it inserts in the wrong position and in the wrong function. Can you please help me with this as I am completely new to perl

Thanks
Jan 18 '11 #1

✓ answered by rski

You need to define range and change within it
Expand|Select|Wrap|Line Numbers
  1. sed  -i  "/function 2()/,/}/ s/variable='\(.*\)'/variable='\1 ggg'/" 1.txt
  2.  

13 3367
rovf
41
I could imagine two approaches:

(1) Your attempted solution processes one line at a time. If you would instead slurp the whole file into a big string, you could then include the function name into your search.

(2) If you prefer processing line-by-line, you can keep track of the functions being seen, and substitute only after you have seen function2. Perls ".." operator could be handy here.
Jan 21 '11 #2
rski
700 Expert 512MB
You need to define range and change within it
Expand|Select|Wrap|Line Numbers
  1. sed  -i  "/function 2()/,/}/ s/variable='\(.*\)'/variable='\1 ggg'/" 1.txt
  2.  
Jan 21 '11 #3
That was such a great answer and worked really really well...Thankss a bunch..I have one more issue....In the above same problem..How do I insert the new string "ggg" exactly after the string "ccc" or so...is there a position based substitution?
Jan 24 '11 #4
rski
700 Expert 512MB
Expand|Select|Wrap|Line Numbers
  1. sed  -i  "/function 2()/,/}/ s/variable='\(.* ccc\)\(.*\)'/variable='\1 ggg\2'/" 1.txt
  2.  
Jan 24 '11 #5
Thnks again...Could you please explain what it does..I especially the 1 and 2
Jan 24 '11 #6
rski
700 Expert 512MB
The pieces
Expand|Select|Wrap|Line Numbers
  1. \(.* ccc\) and \(.*\) 
  2.  
are so called capturing groups.
And \1 and \2 are capturing groups result (so called backreference) so \1 is a string that will match
".* ccc" and \2 is a string that match ".*"
I'm not sure if understand what I mean (is is hard to explain in a few words) so if you google for "regexp backreference" you will find clear explanation.
Jan 25 '11 #7
Thanks a lot! :)
Jan 25 '11 #8
I also had another question. In the same scenario above, how do I set two variables VAR1 and VAR2(both used in function1) to blank at the end of function1(). Do i need to write a small script or if there is a one liner which can search for function1() and set those variables to blank at the end of the function. Thanks
Feb 1 '11 #9
rovf
41
> how do I set two variables VAR1 and VAR2(both used in function1) to blank at the end of function1

This is tricky, because you need to recognize the end of function1. It depends what you know about "function1". For example, if you know that your input files are formatted properly, you can parse the file until you encounter /^function1/, then continue parsing until you encounter /^\}/, and insert your statement just before.
Feb 1 '11 #10
Thanks..lemme try
Feb 1 '11 #11
Thanks rski
Feb 2 '11 #12
Can I have some more clue on this as the function itself has several small blocks of statements with closing curly braces which makes it hard for me to parse exactly till end of function where I need to put my two variables
Feb 2 '11 #13
rovf
41
If we know that the functions are nicely formatted, you just need to have a look at closing braces in column 1.

If this is not the case, you would basically need a Shell script parser, because even counting opening and closing braces would not help (because they might also occur, unmatched, in arbitrary command line arguments, HERE-documents, comments). With other words: If you want to succeed using simple line-by-line reading of your file and checking the lines by regular expressions, you need to specify pretty exactly how the "inside" of your functions might look like. If the answer is "arbitrary shell code", then your analysis program needs to be as powerful as the parser of the shell.
Feb 2 '11 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: beliavsky | last post by:
The code for text in open("file.txt","r"): print text.replace("foo","bar") replaces 'foo' with 'bar' in a file, but how do I avoid changing text inside single or double quotes? For making...
4
by: Jane Doe | last post by:
Hi, I need to search and replace patterns in web pages, but I can't find a way even after reading the ad hoc chapter in New Rider's "Inside JavaScript". Here's what I want to do: function...
0
by: Gerry Viator | last post by:
Hi all, I want to remove the test after a period? Why does the wild card * not work? Dim test As String = "This is just a test report. ERCP" MessageBox.Show(Replace(test, ".*", "."))
4
by: lucky | last post by:
hi there!! i'm looking for a code snipett wich help me to search some words into a particular string and replace with a perticular word. i got a huge data string in which searching traditional...
21
by: gary | last post by:
How would one make the ECMA-262 String.replace method work with a string literal? For example, if my string was "HELLO" how would I make it work in this instance. Please note my square...
0
by: Xah Lee | last post by:
Interactive Find and Replace String Patterns on Multiple Files Xah Lee, 2006-06 Suppose you need to do find and replace of a string pattern, for all files in a directory. However, you do not...
8
by: John Pye | last post by:
Hi all I have a file with a bunch of perl regular expressions like so: /(^|)\*(.*?)\*(|$)/$1'''$2'''$3/ # bold /(^|)\_\_(.*?)\_\_(|$)/$1''<b>$2<\/ b>''$3/ # italic bold...
1
by: rviancha | last post by:
Hi, I am trying to find some funtions that i will use to find a string in many files, the most important thing is that i will use a pattern to do the search.
3
by: Hvid Hat | last post by:
Hi I want to highlight (make it bold) a word in some text I'm getting in XML format. My plan was to replace the word with a bold (or span) tag with the word within the tag. I've found the code...
7
by: nurmaiza | last post by:
HI all, I'm using $content = str_ireplace($search, $replace, $var3); to search and replace value in $var3. My problem is i want to take out all the table attribute found in $var3. For example ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.