Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need a one-liner w/ regex or grep

Status
Not open for further replies.

zackiv31

Programmer
May 25, 2006
148
US
I'm trying to read in a particular part of a string, using substr... and I want to pipe it to grep or sed in order to remove all trailing or ending spaces... so if I have this string:
$string = "a abc d";
$newstring = substr($string,1,4)
$newstring would equal = " abc"... but I want it to equal "abc"

I'm doing this to many different lines of code, so is there a way to pipe it or do it in the same line, I don't want to have to do $string = s/\s+//g; for every line. Just not familiar enough with piping and one-line expressions.
 
use a sub routine:

Code:
my $string = strip_spaces($string);
foreach my $string  (@list_of many_strings) {
    $string = strip_spaces($string);
}

sub strip_spaces {
   my t = shift;
   $t =~ s/^\s+//; #remove all leading spaces
   $t =~ s/\s+$//; #remove all trailing spaces
   return $t;
}

and just feed the sub routine strings or lists as needed.

- Kevin, perl coder unexceptional!
 
Slight syntax error there Kev:

Code:
sub strip_spaces {
   [COLOR=blue]my [COLOR=green]$[/color]t = shift;[/color]
   $t =~ s/^\s+//; #remove all leading spaces
   $t =~ s/\s+$//; #remove all trailing spaces
   return $t;
}
 
I was... errr... just seeing if anyone was... uhh... paying attention.... [flowerface]

(thanks) [talk]

- Kevin, perl coder unexceptional!
 
Using a slightly different method, how about:
Code:
   $string = "a abc d";
   $newstring = (split /\s+/, $string)[1];
     # extract 2nd element from space (or multi-space) separated string

I hope that helps.

Mike
 
WinblowsME

thats just a slower alternative to what I posted. Albeit with $t instead of just t. [wink]

- Kevin, perl coder unexceptional!
 
WinblowsME, not only is it slower (per Kev), it's also incomplete:

Code:
$t =~ s/^\s+|\s+$//[COLOR=green]g[/color];
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top