Operating System - HP-UX
1822728 Members
3741 Online
109644 Solutions
New Discussion юеВ

How to put space in a variable in unix ?

 
SOLVED
Go to solution
Sammy_2
Super Advisor

How to put space in a variable in unix ?

Trying to subsitue 0 with a ' ' (2 spaces) using tr command. But when I run the script , it yields Jun 3 as oppose to Jun(2 spaces) 3.

How can I put spaces using tr or perl/or other unix command ?
Thanks

#!/bin/ksh
###++++++++++++test script ##
MONTH=`date +"%b`
DAY=`date +"%d`
FIRST_CHAR=`echo $DAY|cut -c1`
if [ $FIRST_CHAR = "0" ];then
DAY=`echo $DAY|tr -s '0' ' '`
fi
DATE="$MONTH $DAY"
echo $DATE


###++++++++++++

# ./test
Jun 3


good judgement comes from experience and experience comes from bad judgement.
9 REPLIES 9
TwoProc
Honored Contributor

Re: How to put space in a variable in unix ?

instead of:
DAY=`echo $DAY|tr -s '0' ' '`
use:
echo ${DAY/0/}

and that will remove the offending '0'

We are the people our parents warned us about --Jimmy Buffett
Sammy_2
Super Advisor

Re: How to put space in a variable in unix ?

Thanks John. But I want to replace 0 with a blank space. Would you know how ?
good judgement comes from experience and experience comes from bad judgement.
Tingli
Esteemed Contributor

Re: How to put space in a variable in unix ?

Do you want to use sed? Such as:

DAY=`echo $DAY | sed -e 's/0/ /g'`
Matti_Kurkela
Honored Contributor
Solution

Re: How to put space in a variable in unix ?

If your variable contains spaces, put double quotes around it when using it.

In other words:
replace the last command

echo $DATE

with

echo "$DATE"

MK
MK
TTr
Honored Contributor

Re: How to put space in a variable in unix ?

Your initial thought works ok. The problem is at the end in DATE="$MONTH $DAY". Any leading spaces in $DAY are lost.

Verify it by puting this after the "fi"

echo ":$DAY:"

You will see that $DAY is formatted correctly. The fix is provided by Matti.

Now you can replace the entire shell program with these two lines

DATE=`date +"%b %e"
echo "$DATE"
Sammy_2
Super Advisor

Re: How to put space in a variable in unix ?

You are right, TTR and Matti
I believe Tingli solutionn would work too but double quotes is simpler.
Thanks to all.
good judgement comes from experience and experience comes from bad judgement.
Tingli
Esteemed Contributor

Re: How to put space in a variable in unix ?

Using tr can get one space only. Using sed you can get any number of spaces.
TwoProc
Honored Contributor

Re: How to put space in a variable in unix ?

echo ${DAY/0/}

would become...

$> echo ${DAY/0/X}|tr X " "
3
and it works!

a little too late though ... :-)
We are the people our parents warned us about --Jimmy Buffett
Sammy_2
Super Advisor

Re: How to put space in a variable in unix ?

Tingli - I found that about tr not workign like sed, the hard way.
John J - I will keep your command in my notes and will come in handy.
Thanks so much
good judgement comes from experience and experience comes from bad judgement.