Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here.

Closed Thread    
 
Thread Tools Search this Thread Display Modes
    #1  
Old 07-07-2005
Registered User
 
Join Date: Jul 2005
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
trim whitespace?

I'm trying to find a command that will trim the white space off a string.

e.g.
Code:
$str = "      stuf    "

$str = trim ( $str )

echo $str // ouput would just be stuf

Thanks, Mark
Sponsored Links
    #2  
Old 07-07-2005
Registered User
 
Join Date: Jul 2005
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Oh and stripping out returns, line breaks etc would be nice too.
Sponsored Links
    #3  
Old 07-07-2005
Registered User
 
Join Date: Jan 2005
Posts: 683
Thanks: 0
Thanked 4 Times in 4 Posts
Here is one way to trim spaces (KSH syntax):

Code:
$ str=$(print "$str" | nawk '{gsub(/^[ ]*/,"",$0); gsub(/[ ]*$/,"",$0) ; print }')

You can certainly expand it to eliminate other characters.
    #4  
Old 07-07-2005
bhargav's Avatar
bhargav bhargav is offline Forum Advisor  
Registered User
 
Join Date: Sep 2004
Location: USA
Posts: 512
Thanks: 0
Thanked 2 Times in 2 Posts

Code:
echo "      stuf    " | tr -s " "

OR


Code:
echo "      stuf    " | tr -s " " | sed 's/^[ ]//g

Sponsored Links
    #5  
Old 07-07-2005
vgersh99's Avatar
ɹoʇɐɹǝpoɯ
 
Join Date: Feb 2005
Location: Foxborough, MA
Posts: 7,384
Thanks: 112
Thanked 486 Times in 458 Posts
Quote:
Originally Posted by bhargav
Code:
echo "      stuf    " | tr -s " "

OR


Code:
echo "      stuf    " | tr -s " " | sed 's/^[ ]//g

echo '[ foo ]' | tr -s ' '
[ foo ]

echo ' foo ]' | tr -s ' ' | sed 's/^[ ]//g'
foo ]

echo '[ foo bar ]' | tr -s ' '
[ foo bar ]

echo '[ foo bar ]' | tr -d ' '
[foobar]

echo ' foo bar ' | sed 's/^ *//;s/ *$//'
foo bar
Sponsored Links
Closed Thread

Tags
awk, awk trim, trim, trim awk

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Getting rid of whitespace mosdojaf Shell Programming and Scripting 2 09-20-2010 10:02 PM
How to match (whitespace digits whitespace) sequence? shahanali Shell Programming and Scripting 3 09-19-2010 09:55 PM
echo seems to trim whitespace joeyg Shell Programming and Scripting 2 02-28-2008 03:41 PM
Delete whitespace truck7758 Shell Programming and Scripting 12 12-05-2007 11:00 AM
Trim whitespace and add line break moose1 Shell Programming and Scripting 7 01-22-2007 12:53 PM



All times are GMT -4. The time now is 07:51 PM.