editing text file in perl

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
7/3/2006 7:10:53 AM
comp.lang.perl.misc 32972 articles. 7 followers. brian (1246) is leader. Post Follow

5 Replies
417 Views

Similar Articles

[PageSpeed] 38
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
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
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
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
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
Tad
7/3/2006 1:53:12 PM
Reply:
Similar Artilces:

A97: I want a simple text capture on a website (IE, Edit, Select All, CTRL-C)
After running the following code snippet... MyURL = "http://tycho.usno.navy.mil/what.html" msXML.Open "GET", MyURL, False msXML.send I would like to execute code to perform essentially what would amount to clicking Edit, Select All, CTRL-C in Internet Explorer to capture some basic time 'n date text from the military site and parse it. Someone know how to replicate the effect of the Edit, Select All, CTRL-C keyboard sequence from within code? I'm hoping SendKeys ISN'T the answer. On Mon, 03 Oct 2005 12:39:37 -0400, MLH <CRCI@NorthState.net> wrote: >...

Adding text and date via batch file
Hi, I'm looking for a way to add some text and the date of viewing/printing a pdf document, so that the result would be something like "please view the online version for the latest changes since 02/13/2004" on the top of the page. This should be done from a script (batch file under windows), since we produce quite a few documents which we print to postscript files and convert to pdf automatically. Any hints how this could be done? TIA Jens -- Obige Mailadresse ist g�ltig, wird aber selten gelesen. Schneller geht's mit: jens(Tiefstrich)haug(bei)web(punkt)de ...

Extracting data from messy file...
Hi Folks, I've got a not-so-great looking data file where the data looks something like so: Gibberish 1231 Morestuff 34234 Info1 23 Stuff 32423 DontCare 23421 date 10/04/04 ewrwer 344 dfsdf sdfsdf sd Info2 45 BlahBlah 23423 Gobbleygook EndRecord UhHuh 324 32423 343 34 342 23 35 66 Info1 36 stuffo date 10/04/04 sdfsdf sd f sd4 343 dsf 23423 234 3 3 info2 56 .... EndRecord Unfortuantely, I am not using gawk (and can't install it where I need to run this) so setting RS = "EndRecord" isn't going to work. I was thinking of 1) deleting all blank lines (easy) then 2) Inser...

PB7- crashes when ever highlight / select the edit mask column.
I am using PB7.0 release 5031 and am facing this particular problem where application crashes when the user highlights / selects all the data in the column where editmask is used as edit style. Regards, Virendra. Try to enlarge the column "Vir" <virendrarao@hotmail.com> a �crit dans le message de news: 71d5ed0c.0404012253.67435fcc@posting.google.com... > I am using PB7.0 release 5031 and am facing this particular problem > where application crashes when the user highlights / selects all the > data in the column where editmask is used as edit style. >...

write directory-listing to file or table
Hi, Does anyone have VBA-code or a link to it for the following? I want to write a listing of directories and files to a file or to a table. It's like the old DOS-command dir. dir > lijst.txt Thanks, Vincent See: List files to a table at: http://allenbrowne.com/ser-59alt.html Optionally, filter the file spec, and choose whether subfolders are recursed. -- Allen Browne - Microsoft MVP. Perth, Western Australia Tips for Access users - http://allenbrowne.com/tips.html Reply to group, rather than allenbrowne at mvps dot org. "vincent" <vdb@hotmail.com&g...

SGI for video editing???
I'm new here on this group and just wanted some information about SGI's. Since SGI's can be had for SO little money, I was wondering if they are good for video editing. I have NO knowledge of SGI's and was thinking that it might be worth investigating. Can anyone help me in this area? Steve Wills www.kyvideoservices.com Providing Jimmy Jib services for Film, Video and the Music Industry in Kentucky "Steve" <steventv@insightbb.com> wrote in message news:<LJydc.100097$gA5.1338412@attbi_s03>... > I'm new here on this group and ...

Echoing Comments in MySQL Batch Files to Output
I'm running MySQL 5.0 under Windows XP and typically submit files for batch processing from a command window and redirect stdout to an output file, e.g. mysql --user=root -vvv -t < myfile.sql >myfile.out I'd like to insert what amount to titles in various places in my output file. One way to do this would be to echo comment lines from my sql program file to the output file -- is there a way to do this? Back when I was a SAS user, I could use a command called "title" that worked like: title "This will appear in the output file so you know what you're looki...

Re: DDE to modify an RTF file #3
Hi Paul - I am pretty sure I've evaluated ODS template and it won't cover what we're doing (which is many many custom tables that are pretty well suited to proc report with some modifications). I will revisit and check the paper you suggest - thanks. The reason we haven't used VBA in MSWord is because we want everything self-contained within the SAS program so the programmer doesn't have to remember to run a second non-SAS program to get "final" output. Additionally we have many many programs and each one needs something a little different (different cells merg...

Corrupted Output file #2
11042004 1509 GMT-6 One of the exercises in my Java text is a simple output file that creates a gif image. I had written this file before but after reinstalling Eclipse Im having trouble with this output being corrupted. Here is the code: import java.io.*; public class WriteBytes { public static void main(String[] args) { int[] data = { 71, 73, 70, 56, 56, 97, 15, 0, 15, 0, 128, 0, 0, 255, 255, 255, 0, 0, 0, 44, 0, 0, 0, 0, 15, 0, 15, 0, 0, 2, 33, 32, 127, 161, 200, 185, 205, 84, 128, 241, 81, 35, 175, 155, 26, 228, 254, 105, 33, 102, 121, 165, 201, 145, 169, 154, 142, 172, 116, 162, 240,...

Makeing Scales Not Editable
Hi there, &nbsp; I have a user interface that I'm building into an application with application builder. &nbsp; I have about a dozen Slider controls.&nbsp; The problem is that they can currently be changed by the final user.&nbsp; I'd like to have them fixed at 'compile' time.&nbsp; I know I can do this programatically by dropping a property node for the slider and setting the scale/editable property to false... is there a simpler way to do this? &nbsp; Thanks in advance for any responses. &nbsp; Derek Dereklogitech wrote: So it's the scale not...

SW student edition
The educational / student edition of SW which can be purchased by a student from various resellers, (for example: http://www.gradware.com/product/view/849761) allegedly "contains features that make it unsuitable for commercial use." What are these features? > What are these features? Watermark that warns it's not for commercial use. Jon Banquer San Diego, CA > Watermark that warns it's not for commercial use. A cautionary Warning from the San Jose user group meeting last week relating to "student-version" parts on 3d content central: I had lunch ...

solutions manual, test bank for Decision Support and Business Intelligence Systems International Edition 9e 9/E 9th Edition by Efraim Turban Ramesh Sharda Dursun Delen contact directly at studentshelp
Decision Support and Business Intelligence Systems International Edition 9e 9/E 9th Edition by Efraim Turban Ramesh Sharda Dursun Delen solutions manual and test bank available at best price contact at studentshelp(at)hotmail(dot)com Decision Support and Business Intelligence Systems International Edition 9e 9/E 9th Edition by Efraim Turban Ramesh Sharda Dursun Delen ...

US-VA-McLean: VMS Systems Mgr, Config, VMS, DCL, csh, Perl, UNIX, NT; C-P (45302657613)
US-VA-McLean: VMS Systems Mgr, Config, VMS, DCL, csh, Perl, UNIX, NT; C-P (45302657613) ======================================================================================= Position: VMS Systems Mgr Reference: SMC01430 Location: McLean VA Duration: C-P Skills: 2+yrs system administration, specifically VMS System Management. Configuration of VMS systems, system Installation, clustering and configuration, security, installing third-party software. Paging and swapping, inter-process communication, device...

4.12a text attachment
Attention Beta-testers. Pegasus has been known to muck up text attachments if default settings are used - it tags the attachment as: Content-description: Text from file 'filetype.pm' which loses the file name when saving and distorts 8-bit content So to avoid these errors, one had to change the encoding from "Mailer decides" to "Basic MIME" (or some other). Up to version 4.02a, there was an automatic fix for this: 1. Include in filetype.pm something like: Text,0,X,0,.TXT,X,0,.PND,X,0,.INI,X,0,.PM,X,0,.PMC,X,0,.PML,X,0,.PNP,X,0,.CN M , and, t...

PPC Mac Edition
Is Wine ready for PPC Mac's? dqboy101 wrote: > Is Wine ready for PPC Mac's? Wine is only usable on i386 and amd64/x86_64 machines, unless you have a *really* fast PPC processor and a good virtual machine running i386 Linux (or just run Windows for that matter). But it won't integrate directly into your PPC-based OS (MacOS or PPC Linux), as far as I know. Mike Freeman On Tue, 02 Sep 2008 15:28:05 -0700, Michael and Nicole Freeman <mnfreeman@cox.net> wrote: > Wine is only usable on i386 and amd64/x86_64 machines, unless you have a > *really* fast ...

re: CD text
I have determined that there is text on the cd a label prog displays it but PM123 does not is there one that will ...

Re: How to retrieve column or variable names from a file?
Hi Peeyush, One of many solutions is: PROC CONTENTS DATA=dataset OUT=MetaData (KEEP=Name); RUN; Regards - Jim. -- Jim Groeneveld, Netherlands Statistician, SAS consultant home.hccnet.nl/jim.groeneveld My computer is a long way from home and only sparsely can access SAS-L. On Thu, 4 Jan 2007 02:43:16 -0500, Peeyush Agarwal <Peeyush.Agarwal@EVALUESERVE.COM> wrote: >Dear All, > >Is there a quick way to retrieve in a single column of a file, all the >column (=variable) names in a file? > >Thanks in advance and Regards, >Peeyush ...

Merging project files... can it be done?
Hi, I'm currently integrating Apache's xerces XML parser into our application. Thankfully, it already comes with a Win32 Codewarrior project and a Mac OS project! But our application is cross-platform and has a Win32 and Mac OS X target. I'd like to know if it's possible to merge separate projects into one, so, like in this case, I'd have one project to build build Mac and Win32 targets. I would guess if it's possible, it'd have something to do with merging an exported XML project file? Would I be warm? Thanks for any help. Steve. PS. Oh, btw...

new at "awk.info": playing zork, info bots, text tools
Here are the recent updates to http://awk.info . (For all updates to awk.info, subscribe to http://tinyurl.com/rss4awk. To contribute to awk.info, see http://awk.info/?contribute .) ----------------------------------------------------------- TOOLS Praveen Puri offers a Zork-clone, in Awk. - http://awk.info/?game Ed Morton sorts out everything (using Awk): - http://awk.info/?sorting Is this the smartest (smallest) formatter ever written? - http://awk.info/?tools/columnate Gregory Grefenstette implements Norvig's spell checker - http://awk.info/?tools/spellcheck Pierre Gaston calculat...

Copying file from Cisco switch to VAX/VMS
Hi VMS masters: I need copy flash:config.txt file from Cisco switch to my VAX/VMS system. When I issue: copy flash:config.txt ftp://user:password@ip_address/[directory]file.txt I get writing... (permission denied) What can I do to enable cisco switch do write this file in my vax ? Need I create a proxy account ? issuing ucx sh services in my vax I get : ftp telnet Thanks in advance ! ------=_Part_34728_18829034.1152287274254 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline If you're using a pc as a terminal, sim...

Problem overwriting init.m file
On March 1, 2006, Arnoud Buzing made a posting about creating kernels. I tried it out as I was having a problem creating a remote kernel (the post follows below) and lost the contents of my init.m file - much to my surprise and disappointment. Why would this code cause the init.m file to be replaced (really what was lost was the kernel definitions I had already created - none of them were named "Remote", but of course I did have a local that I didn't care about. Any suggestions about how to prevent Mathematica from overwriting this important file, that might have taken ma...

Gzip -d to a specific file
consider using : gzip -d abc..txt.gz , it will become abc.txt is it possible to unzip to def.txt without using `mv` ? thanks. On 2006-08-29, howa <howachen@gmail.com> wrote: > consider using : > > gzip -d abc..txt.gz > > , it will become abc.txt You either have a typo or are just incorrect. It will uncompress to abc..txt. > is it possible to unzip to def.txt without using `mv` ? You can use zcat or gzip -dc to uncompress to stdout, then redirect to another file: zcat abc..txt.gz > def.txt This will leave abc..txt.gz intact. man gzip for more details. --...

Re: Renaming a .lst file in batch #3
Dear SAS-L-ers, Eric posted the following: > I'm sure somebody should be able to figure this out quickly, > but I've been stuck on this for a while and am finally > searching out some help. > > I've got a program which creates several listings of various > types (data null output, procedural output and several proc > sql queries at the end). After the end of the SAS statements > I have a Unix command that renames the file to .doc from .lst > and then emails the file to me (for now while I'm testing). > The .lst file appears to be incomplete when ...

Compare text in columns
Hi all, I tried posting this last night, but it doesn't seem to have worked. I am trying to compare 2 lists of words using LabView.&nbsp; My example was something like this: I have 1 column containing M words: ball jack jill barbecue lamb etc.. and one containing N passages of text.&nbsp; jack and jill went up the hill... mary had a little lamb... see spot run... etc... I want to test a logical condition like: If 1st entry from colum1 is in 1st entry from column2 then return 1, if not return 0.&nbsp; If 2nd entry from colum1 is in 1st entry from column2... etc The ...

LZX code in CAB files
Hi all I need code of LZX compressor and decompressor which is implemented in the CAB files for testing. Please give me any reference from where I may get code. Regards:- -Gurjant Singh ...