• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 334
  • Last Modified:

How to find lines beginning with particular characters

Hi Experts,

How do I check if a line starts with, say for example, character 'A'.

In the following three lines, only the 2nd should pass this check

Banana republic
Arctic ocean
Canberra kangaroo


if( line begins with 'A')    <---- I want the perl equivalent to do this.
{


}

0
ambuli
Asked:
ambuli
  • 5
3 Solutions
 
farzanjCommented:
Short answer:

Matching with

if ($line =~ "^A")
{

}

Need full code?
0
 
ambuliAuthor Commented:
Thank you.  I will ask another question.  I want to check if the third character is numeric in a line.  I increased the points too :-)


S 13:08:30
   ^
0
 
farzanjCommented:
Here is the complete code just to show this
#! /usr/bin/perl

use strict;
use warnings;

my $file = 'data.txt';

open IN, $file or die "Could not open $!";
my @lines = <IN>;
close IN;

foreach my $line (@lines)
{
        if ( $line =~ "^A")
        {
                print $line;
        }
}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
farzanjCommented:
Third character is a number

if ($line =~ "^..\d")
0
 
farzanjCommented:
Sorry use this

if ($line =~ /^..\d/)
0
 
farzanjCommented:
A better way would be


if ( $line =~ /^.{2}\d/ )
        {
                print $line;
        }
}

Explanation: ^ start of line
.{2} Any two characters
\d a numeric character.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now