Operating System - HP-UX
1827703 Members
2841 Online
109967 Solutions
New Discussion

script to add variable in one line

 
SOLVED
Go to solution
kholikt
Super Advisor

script to add variable in one line

Hi,

I have script with the following:
CL="ABC:BCD:CDE"
ID=1
IFS=:

for i in $CL
do
CL_GRP="${CL_GRP} $i $ID"
done
echo CL_GRP

The output should be
'ABC' 1 'BCD' 1 'CDE' 1

but the problem is how can I have the ' sign and the method above seems to always generate one empty space.
abc
6 REPLIES 6
Steven Schweda
Honored Contributor
Solution

Re: script to add variable in one line

> echo CL_GRP

Do you mean?: echo $CL_GRP

> [...] the method above seems to always
> generate one empty space.

Are you complaining about the space at the
beginning of CL_GRP? If so, then, as usual,
many things are possible. For example, one
could use "sed" to remove a leading space:

echo $CL_GRP | sed -e 's/^ //'

Or, one could avoid putting the space in at
the beginning:

first=''
for i in $CL
do
if [ -z $first ]; then
CL_GRP="$i $ID"
first='no'
else
CL_GRP="${CL_GRP} $i $ID"
fi
done

Or (saving a variable):

CL_GRP=''
for i in $CL
do
if [ -z $CL_GRP ]; then
CL_GRP="$i $ID"
else
CL_GRP="${CL_GRP} $i $ID"
fi
done



(So, people don't learn basic computer
programming nowadays?)
kholikt
Super Advisor

Re: script to add variable in one line

Is there anyway that I can add ' to each CL

for example 'ABC' 'BCD' 'CDE'

instead of ABC BCD CDE
abc
Steven Schweda
Honored Contributor

Re: script to add variable in one line

> Is there anyway that I can add ' to each CL

What did you try?

CL_GRP="'$i' $ID"

(and so on)?
kholikt
Super Advisor

Re: script to add variable in one line

I have tried

CL="${'CL'} $i"

but it doesn't return as 'ABC''BCD' 'CDE'
abc
Steven Schweda
Honored Contributor

Re: script to add variable in one line

> I have tried
>
> CL="${'CL'} $i"
>
> but it doesn't return as 'ABC''BCD' 'CDE'

Yeah. I can see why. Can you? Did you try
what I suggested?

${'CL'}

Really? Where do you want the ' characters?
Around the old stuff (CL) or around the new
stuff (i)?

Inside the braces? ${CL} makes sense to me.
'${CL}' makes sense to me. ${'CL'} makes no
sense to me. (Or to the shell?)
Joseph Steinhauser
New Member

Re: script to add variable in one line

If using ksh or posix-shell, you can also clean-up your extra space by using

${VARIABLE%% } to trim trailing spaces.

So your script would become:

for i in $CL
do
CL_GRP="${CL_GRP%% } $i $ID"
done
echo "CL_GRP=\"${CL_GRP}\""

Old School efficiency. New World Tools.