editing text file in perl

  • Permalink
  • submit to reddit
  • Email
  • Follow


I want to edit a perticular line in a 50 lines text file using perl.

File handle can be used for this.
But how can i edit  a string present in say 20th line  using perl
script.

0
Reply hara.acharya (48) 7/3/2006 7:10:53 AM

See related articles to this posting


king wrote:
> I want to edit a perticular line in a 50 lines text file using perl.

That's a FAQ.

     perldoc -q "change one line"

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
0
Reply Gunnar 7/3/2006 7:26:16 AM

king wrote:

> I want to edit a perticular line in a 50 lines text file using perl.
>
> File handle can be used for this.
> But how can i edit  a string present in say 20th line  using perl
> script.

  #!perl
  use strict;
  use warnings;
  my $file         = 'file.dat';
  my $line_counter = 0;
  my $new_content;

  open my $F, '<', $file || die "Cant open $file: $!";
  flock($F, 1) || die "Cant get LOCK_SH on $file: $!";
  while(<$F>)  {
    $line_counter ++;
    if ($line_counter == 20)  {
      # do something on 20th line, eg. change it
      $_ = "this is new content of line 20\n";
    }
    $new_content.= $_;
  }
  close $F || die "Cant close $file: $!";
  
  # report
  print $new_content;

Hope this helps,

-- 
 Bart

0
Reply Bart 7/3/2006 7:27:07 AM

Bart Van der Donck wrote:
> king wrote:
> 
> 
>>I want to edit a perticular line in a 50 lines text file using perl.
>>
>>File handle can be used for this.
>>But how can i edit  a string present in say 20th line  using perl
>>script.
> 
> 
>   #!perl
>   use strict;
>   use warnings;
>   my $file         = 'file.dat';
>   my $line_counter = 0;
>   my $new_content;
> 
>   open my $F, '<', $file || die "Cant open $file: $!";
>   flock($F, 1) || die "Cant get LOCK_SH on $file: $!";
>   while(<$F>)  {
>     $line_counter ++;
>     if ($line_counter == 20)  {
>       # do something on 20th line, eg. change it
>       $_ = "this is new content of line 20\n";
>     }
>     $new_content.= $_;
>   }
>   close $F || die "Cant close $file: $!";
>   
>   # report
>   print $new_content;
> 

I prefer to keep simple jobs simple :-)
  perl -pi -e 'if ($.==20) {s/^.*$/new content for line 20/;}' file.dat
or
  perl -pi -e '($. == 20) && s/^.*$/new content for line 20/;' file.dat
0
Reply Ian 7/3/2006 9:44:12 AM

Ian Wilson wrote:
> I prefer to keep simple jobs simple :-)
>  perl -pi -e 'if ($.==20) {s/^.*$/new content for line 20/;}' file.dat
> or
>  perl -pi -e '($. == 20) && s/^.*$/new content for line 20/;' file.dat

'short' ne 'simple'

-- 
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
0
Reply Gunnar 7/3/2006 11:19:30 AM

Gunnar Hjalmarsson <noreply@gunnar.cc> wrote:
> Ian Wilson wrote:
>> I prefer to keep simple jobs simple :-)
>>  perl -pi -e 'if ($.==20) {s/^.*$/new content for line 20/;}' file.dat
>> or
>>  perl -pi -e '($. == 20) && s/^.*$/new content for line 20/;' file.dat
> 
> 'short' ne 'simple'


And attempting to re-answer a Frequently Asked Question is neither.


-- 
    Tad McClellan                          SGML consulting
    tadmc@augustmail.com                   Perl programming
    Fort Worth, Texas
0
Reply Tad 7/3/2006 1:53:12 PM
comp.lang.perl.misc 32807 articles. 7 followers. Post

5 Replies
282 Views

Similar Articles

[PageSpeed] 23


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Editing a text file and then replacing existing file
I have a script that I use to find text in a file and then delete the line(s) the text is on. That part works. What I have been unsuccessfully trying to do is take the new text and overwrite the existing file that I did the search and delete on. Here is my existing code that finds the lines and deletes them: path='c:\ruby192\my_projects\IIS_Logs\ex11012607.log' search_text = %r{/memberinfo/downline/tree/can.asp} search_text2 = %r{/memberinfo/downline/tree/disto.asp} search_text3 = %r{/styles/default.css} search_text4 = %r{/scripts/generalscript.js} search_text5 = %r{/member...

Select and get text from Edit text filed
Hi, I need to make a simple text editor in matlab gui. I want is the user to be able to select part of the text he had typed and make the fontweight bold. I don't know how to get the selected text. Can you give me some clues? Thanks. ...

Viewing text files in GUI Edit Text boxes
Hi, I am importing a text file containing numeric and character or just numeric data (of unknown size) and I want to view the contents in a GUI Edit Text box. I've thus far managed to format a string of the numeric only file and view it: datastr=sprintf('%-12.3f',handles.rawdata); set(handles.fdesc,'Visible','on','String',datastr) But, say the file is 20x20 will display the first four numbers of each column then move to the next line and display the next 4, etc. Is there anyway to: a) Add breaks in the data to show the user that the next set of data is f...

Reading Text File, Text Scrolling and erase line from a text file
Hi , How can I Reading Text File, then Text Scrolling by means of keys "page UP" "page Down" and erase a specific line from a text file , when press "F2" key? Best Regards, Lidia from Poland -- ========================================= Pozdrawiam Lidiaa Lidiaa schrieb: > Hi , > > How can I Reading Text File, then Text Scrolling by means of > keys "page UP" "page Down" and erase a specific line from a text > file , when press "F2" key? > > ...

Viewing text files in GUI Edit Text boxes #2
Hi, I am importing a text file containing numeric and character or just numeric data (of unknown size) and I want to view the contents in a GUI Edit Text box. I've thus far managed to format a string of the numeric only file and view it: datastr=sprintf('%-12.3f',handles.rawdata); set(handles.fdesc,'Visible','on','String',datastr) But, say the file is 20x20 will display the first four numbers of each column then move to the next line and display the next 4, etc. Is there anyway to: a) Add breaks in the data to show the user that the next set of data is f...

How to save text files in Matlab GUI from edit text box
Dear all, please help me in understanding the usage of GUI. I found on the web a suggested way to write a button callback to read the content of an edit text box and save to a txt file, that is: %save text of command.txt file fid = fopen('command.txt','wt'); fprintf(fid,'%c',get(handles.edit1,'String')) fclose(fid); Anyway, the text in the box is saved in the text file in a wrong and very peculiar way; if I write in the box something like: PALA POLO I find in the command.txt file has been saved the following: PPAOLLAO and I can't manag...

Edit text from a file
Hi! I need to know how I can delete some text from a text ascii file. I want to read from the line number 7 (where numbers start). In the example below, I would need to extract the second and third columns of the data. Thank you in advances for your answers. An example: ===================================================== TRANSFORMADO CON MODELADO DE DISTORSIÓN MÍNIMA CURVATURA VERSION 3.x REPORTE DE BUGS: FJGMATESANZ@FOMENTO.ES Transformado a DATUM ED50 ======================================================= 1 604070.688 4114558.386 30 -23.916 1 49 40.06276 W 37 10...

editing text file
Hi ! I have a text file with 360000 lines like this : 95640 LE HEAULME 95640 MARINES 95640 NEUILLY EN VEXIN 95640 SANTEUIL and I would like to convert all the line like this with a shell script : "95640";"LE HEAULME"; "95640";"MARINES"; "95640";"NEUILLY EN VEXIN"; "95640";"SANTEUIL"; how can I do that ? On Thu, 08 Apr 2004 at 21:06 GMT, Slasher wrote: > Hi ! > > I have a text file with 360000 lines like this : > > 95640 LE HEAULME > 95640 MARINES > 95640 NEUILLY EN VEXIN > 95640 SA...

Edit a text file
Does someone have some sample code to read a space delimited ASCII file into a QUEUE and then load a Browse list with the queue data? I'm having troubles. THX. ...

Editing Text Files
I have text files full of "blahblahblah". I want to add "morestuff" to the beginning of each line, and "theend" to the end of each line. So, the result will be that the text files, presently full of line after line of "blahblahblah" will now have line after line of "morestuffblahblahblahtheend". How do I do this, other than manually editing the file? I know there's some program that will do it. sed? I've never used sed, I'm not exactly sure what it does. Any help would be appreciated. Thanks. -Dan On 2003-11-15, Dan <di...

text from a editable to a file
Hi! I'm making a GUI and i'm using a editable in which it is possible to write more than one line. Then I would like to write those lines in a file. I use this sentence: fprintf(fid, '%s',edit_string) But it mixes both lines in one and the message can not be read. Can anyone help?? "Izaskun Azk" <izaskunazkarate@gmail.com> wrote in message <gbvmq6$37h$1@fred.mathworks.com>... > Hi! > I'm making a GUI and i'm using a editable in which it is possible to write more than one line. Then I would like to write those lines in a file. I use this ...

Editing a text file
There is a task to edit a text file. It is entirely possible that multiple people are going to be running the ruby script that edits this file at the same time. I have looked at Ruby cookbook recipe 6.13 and 20.11. These seem like what I am wanting. It seemed like a good idea to float this as a solution before it is implemented. How I do it now is using sed: flock $USERFILE sed -i \ "/^$1[[:space:]]\+/,+6 { s/^\\(.*Default\\)/#\\1/; s/^#\\(.*SRT\\)/\ \1/; }" \ $USERFILE But I'd like to move this piece of code into the ruby script instead of launching it with a system ...

How to edit a text file ?
i wanna build a text editor,and now idk how to editor a file when i open..for example..if i use cout to show the text's content..and ill cannot to move my cursor to the content and edit... This is a MIME GnuPG-signed message. If you see this text, it means that your E-mail or Usenet software does not support MIME signed messages. The Internet standard for MIME PGP messages, RFC 2015, was published in 1996. To open this message correctly you will need to install E-mail or Usenet software that supports modern Internet standards. --=_monster.email-scan.com-12776-1364703601-0002 Con...

Edit text files
Hi, I'm working with VxWorks version 5.5 embedded in a board with a PowerPC 860. The communication between my computer and the PowerPC is via serial port. I need to modify some text files in the this board but I don't know how. Have the VxWorks some text editor like vi or nano? This board that I'm using is a prototype from another enterprise then a can't modify it, the only way to access its configurations is via serial port. Thanks. Hi: No editors built in. Where are the files stored? Are they in a file system you can export or in a flash image of a ram drive that you c...

Editing text file
Hi, I want to change a version number in 4 text files. The 4 files are not the same, but the changes will be the same. For example. I want to change "version 1.0" to "version 1.1". The files do have more information than this and that information should remain unchanged, and the location of version 1.0 is not always the same in the file. Is it possible to do this for all the files at once? If it is not, how would u do it for one file at a time? Thank you in advance "Bojan" <srbijan@gmail.com> wrote: >I want to change a version numb...

Call a Edit text from Edit text in another gui ?
PhatHienLSB.m function PushMo_Callback(hObject, eventdata, handles) % hObject handle to PushMo (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [filename, pathname] = uigetfile( ... { '*.bmp','BMP (*.bmp)'; ... '*.png','PNG(*.png)'; ... '*.jpg', 'JPG (*.jpg)'; ... '*.*', 'All Files (*.*)'}, ... 'Moi ban chon tep anh'); set(handles.Edit1,'String',[filename,pathname]); TachTin.m function T...

concatenating multiple text files into one text file
Hello all, I have a huge number of text files like : spectrum1_300_315.csv spectrum1_315_331.csv spectrum1_331_364.csv spectrum1_364_386.csv spectrum1_386_401.csv ...................................... ....................................... each file contains some headerlines at the beginning and data in 2 columns. I want to concatenate the data of the files into one text file .Can anyone hel me pls?thank u in advance. ...

Converting A Unicode Text File to An ASCII Text File
We have a large number of text files built in Unicode that we need to be read by SAS. SAS does not read Unicode text. To convert the Unicode text to ASCII text we did the following: A Unicode text file adds an additional blank space to each character. To remove this blank character, you can use the code below. The hexidecimal value '00' is a blank character. So remove it using the SAS statement '00'x. The 'x' tells SAS you are reading hexidecimal. Use RECFM=N to tell SAS that you are reading a stream of data that will not conform to a typical file structure. SAS will ...

Failed to write to a text file (text file is RW)
Hi, I dig up the following script. Added a simple HTML file with a form field named "vote" and have it send to the following php script. However, it failed to write to the poll_result.txt file. Why? Thanks as usual. <?php $vote = $_REQUEST['vote']; //get content of textfile $filename = "poll_result.txt"; $content = file($filename); //put content in array $array = explode("||", $content[0]); $yes = $array[0]; $no = $array[1]; if ($vote == 1) { $yes = $yes + 1; } if ($vote == 0) { $no = $no + 1; } // debug echo $yes; echo $no; // ou...

How to format a text file just like the RFC-text files?
I want to make some document go like these, what tools can help? Any help would be nice, thanks! BLIOGRAPHY ........................................... 34 APPENDIX A. EXAMPLES ............................................... 36 B. SIMPLE FIELD PARSING ................................... 40 C. DIFFERENCES FROM RFC #733 .............................. 41 D. ALPHABETICAL LISTING OF SYNTAX RULES ................... 44 August 13, 1982 - i - RFC #822 ^L Standard for ARPA Internet Tex...

how to cut a text file in perl
hi i have a log file that it is increasing to big, how can i keep this file of a certain size, in other words, how can i make sure that the file is only 200 lines long and delete the first lines if longer. i think it would be easier to write this in a shell script. but i have no idea in perl. can anyone tell me how to print the last 200 lines of a file and overwrite the ssame file. thanks. Joseph wrote: > hi i have a log file that it is increasing to big, how can i keep this > file of > a certain size, in other words, how can i make sure that the file is > only 200 lines long an...

Saving a file in Text Edit
I have created a file from a post on this group by selecting, then copying and pasting the wanted text from the post into text edit using plain text. I used "save as" and assigned a name to the file then saved it to the documents folder. The file saves all right, but when reopened constantly opens in a small window that is barely legible. I'm trying to resize the text using the apple/shift/+ combo to a full size window and larger text, then re-save the file to have it read larger when reopened again. This isn't working for some reason. Am I doing something wrong? Dudley...

text file edit object?
# Does anything like this exist ? myfile = TextFile("myfile.c") if myfile and myfile[0].startswith( "/*" ): myfile[:12] = [] myfile.save() # Simon Burton. Please ignore, my news reader went crazy. Simon. On Tue, 24 Feb 2004 09:57:03 +1100, Simon Burton wrote: > > # Does anything like this exist ? > > myfile = TextFile("myfile.c") > if myfile and myfile[0].startswith( "/*" ): > myfile[:12] = [] > myfile.save() > > > # Simon Burton. ...

Editing PDF files with perl
I have a number of PDF files. I would like, for all of them, to remove the "page before last". In addition, they contain a watermark that I want to remove. These files are not copyrighted since they contain the works of the US government. So please, no self righteous copyright comments. There seems to be a multitude of PDF perl modules. Is there any one specifically suited for editing pdf files. i Ignoramus3188 <ignoramus3188@NOSPAM.3188.invalid> wrote: > I have a number of PDF files. > > I would like, for all of them, to remove the "page ...