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 32779 articles. 7 followers. Post

5 Replies
202 Views

Similar Articles

[PageSpeed] 46


  • 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...

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...

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. ...

.jpg files to editable text---how?
Running Win XP. I have tables consisting of columns---some colums have short blurbs of text, some numbers. All are neatly arranged in tabular form. There are three pages of tablular data. The tables are in 3 separate .jpg files. How do I get this into editable files so I can work with the data using Word or MSWorks? I can print 'em out, no problem. They come out looking fine. I then tried scanning as editable text and graphics, and editable text. Either way produces gobbledegook. Not a good or useable OCR conversion. What next???? ...

edit text in a txt file
hi all, here is the php code! i am trying to use to 'edit' hyperlink to edit txt in member.txt. Problem is that it reads the values ok into an array, however when i attempt and update new values into the file, i get no results. Does anybody know where i am going wrong???? <? session_start(); // Set updated content for user if(!isset($_POST[Submit])) { // read content from file and place into array, this is used to put initial content into form $fc=file("../username/member.txt"); $userid_no = $_GET['record_id']; $line = split("\|",$fc[$us...

text/ data file editing
Hi All, I'm having two text/ data files with the following content. Table1 101 Red 102 blue 103 green 104 black 105 yellow Table2 Rayan 102 Toy 101 Jeff 104 Cathy 103 st 105 The output file (Table3) should come like below .. Table 3 101 Toy 102 Rayan 103 Cathy 104 Jeff 105 st Please, help me in writing a oneline / small script to achieve Table 3 output from Table1 and Table 2 data. Thanks in advance, an. In comp.unix.shell anju <anjani.unix.help@gmail.com>: > Hi All, > I'm having two text/ data files with ...

editing pdf files with perl
Hi, I have a collection of PDF files which are stored in a directory. These PDF files follow a particular format. Each one of these files has some fields in the first page which are left blank. I need to fill those fields based on the input given by the user(s). I CANNOT overwrite these PDF files since the data contained in them is not elsewhere. I simply need to be able to edit and update the first page of these PDF files. Is there any way I can do this with Perl? Thanks in advance :) Aditya <aditya2507@gmail.com> wrote in message news:1108405623.370567.287490@o13g2000cwo.google...

text file edit object
# Needed to edit a text file like a list: file = TextFile( "foo.txt" ) del file[:-10] # remove last 10 lines file.save() # Ended up writing this: #!/usr/bin/env python from tempfile import mktemp import shutil import sys class TextFile(list): def __init__(self,name): file = open( name ) self[:] = file.readlines() self.name = name def save(self): temp = mktemp() file = open( temp, "w" ) file.writelines( self ) file.close() #tgt = "_"+self.name tgt = self.name #print temp, tgt shutil.copy( temp, tgt ) # Is ther...

editing a text file with matlab
I am trying to open up text file with matlab and change 3 values from a vector. For instance wi have a text file and i want to go to the 10th line of the text and edit 3 values <0,1,0>, <.5147,-1.6694,-.1925> in this case i want to have as variable the .5 the -1.6 -.19. As enter the new values iwant to save this edit text file as a new text file. thanks, V. > I am trying to open up text file with matlab and change 3 values > from > a vector. > For instance wi have a text file and i want to go to the 10th line > of > the text and edit 3 values <0,1,0>, > ...

edit text in a file and save it again
I must be overlooking something here... I'm trying to edit a line in a text file. I thought this was easy with fileinput, but all examples do not write the line back to the file but simply 'print' it. I want to open the file, edit the line and save it again. Is fileinput the right module for that? At Sunday 19/11/2006 20:07, cyberco wrote: >I must be overlooking something here... I'm trying to edit a line in a >text file. I thought this was easy with fileinput, but all examples do >not write the line back to the file but simply 'print' it. I want to >open...