By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,178 Members | 987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,178 IT Pros & Developers. It's quick & easy.

extracting a string

P: 4
i have a input file of the format

0000GH000
0000GH000
0000NM000

How would i extract GHGHNM from this input file using perl scripts
Nov 20 '08 #1
Share this Question
Share on Google+
6 Replies


nithinpes
Expert 100+
P: 410
What have you tried? You can do it using regular expressions.
Nov 20 '08 #2

P: 4
i am new to perl
hardly a weeks experience

i have tried this way

if ($string =~ /^CPDS/)
{
if ((substr($string, 38, 2) ne " "))
{
@chk = $string;
foreach $rec1 (@chk)
{
$chk1 = substr($rec1, 38, 2);
}
print "$chk1";
}

}
this code prints my desired result on console
but when it's printed on the file , i can see only the last 2 characters
Nov 20 '08 #3

nithinpes
Expert 100+
P: 410
The script you have posted has no relevance to the data that you posted initially. According to your initial posting, you were trying to extract two non-digits(alphabets) from each line and appending them. the following code will do that:
Expand|Select|Wrap|Line Numbers
  1. use strict;
  2. open(DATA,"inputfile") or die "failed:$!";
  3. my $str="";
  4. while(<DATA>) {
  5. chomp;
  6. my $ch=$1 if(/(\D\D)/) ;  # extract consecutive non-digits
  7. print "$ch\n";
  8. $str.=$ch;   # append 
  9. }
  10. print "$str";
  11.  
If this does not solve your problem, please be more clear on what exactly you need.
Nov 20 '08 #4

P: 4
i tried this but this does not give my desired result .
this is how it is supposed to work

first it looks for records starting with CPDS
then with in those CPDS records it checks whether position 38,2 is not null
if it's true
it has to get this 38,2 substring from all the choosen records
so that each substring would be concatenated to become a single string.

when i tried with ur code part it worked this way
LK
LKWN
WNPR
PR
Nov 20 '08 #5

nithinpes
Expert 100+
P: 410
i tried this but this does not give my desired result .
this is how it is supposed to work

first it looks for records starting with CPDS
then with in those CPDS records it checks whether position 38,2 is not null
if it's true
it has to get this 38,2 substring from all the choosen records
so that each substring would be concatenated to become a single string.

when i tried with ur code part it worked this way
LK
LKWN
WNPR
PR
Could you provide sample data from your file?
Nov 20 '08 #6

P: 4
am sorry my friend

it worked
I was using ur code a different way initially . This is just a small part of the whole code . i really had to integrate ur logic with my program's logic.

anyway thanks a lot
Nov 20 '08 #7

Post your reply

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