Ensuring A String Doesn't Begin With Space


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Ensuring A String Doesn't Begin With Space
# 1  
Old 09-03-2008
Question Ensuring A String Doesn't Begin With Space

In my continuing struggle with my menu for record manipulation, I've been scripting to add records to the 'records' file. For the most part, I've been successful. I am, however, running into a strange problem.

Code:
                                while [ ! $gn_correct ]
                                do
                                        echo -n "Given name: "
                                        read g_name
                                        if [ ! $g_name ] ; then
                                                echo "Given name not entered."
                                        elif [ `expr substr $g_name 1 1` = " " ] ; then
                                                echo "Given name may not begin with a space."
                                        elif [[ $g_name = $(echo "$g_name" | tr -dc '[A-za-z ]') ]] ; then
                                                gn_correct=1
                                                echo -n "$g_name:" >> records
                                        else echo "Given name can contain only alphabetic characters and spaces"
                                        fi

                                # Close given name loop.
                                done

The above code reads in a person's given name. It makes sure that a name has been entered, then proceeds. The problem lies here:

Code:
elif [ `expr substr $g_name 1 1` = " " ] ; then
                                                echo "Given name may not begin with a space."

The idea is to test to make sure the first character in the string received for the given name is not a space and return an error-echo if it is. It'll then repeat the loop, so the user is given another opportunity to get it right. In theory this continues until a valid given name is received.

However, it doesn't work this way. Instead, this code is skipped over. Spaces are truncated from entries with a leading space anyway - but the problem is, I'm using this same code to collect job title information. Job titles often have spaces in them (though not at the start.)

The expr continues to fail at picking up leading spaces - but, more strangely, if there is a space somewhere else in the string, expr encounters a syntax error, and the echo displays that a job title may not begin with a space.

Any suggestions on how I could detect leading spaces and produce an error, while still allowing spaces elsewhere in the string?

Thanks in advance for help,
Wolfie
# 2  
Old 09-03-2008
Quote:
Originally Posted by Silentwolf
In my continuing struggle with my menu for record manipulation, I've been scripting to add records to the 'records' file. For the most part, I've been successful. I am, however, running into a strange problem.

Code:
                                while [ ! $gn_correct ]
                                do
                                        echo -n "Given name: "
                                        read g_name
                                        if [ ! $g_name ] ; then
                                                echo "Given name not entered."
                                        elif [ `expr substr $g_name 1 1` = " " ] ; then
                                                echo "Given name may not begin with a space."
                                        elif [[ $g_name = $(echo "$g_name" | tr -dc '[A-za-z ]') ]] ; then
                                                gn_correct=1
                                                echo -n "$g_name:" >> records
                                        else echo "Given name can contain only alphabetic characters and spaces"
                                        fi

                                # Close given name loop.
                                done

The above code reads in a person's given name. It makes sure that a name has been entered, then proceeds. The problem lies here:

Code:
elif [ `expr substr $g_name 1 1` = " " ] ; then
                                                echo "Given name may not begin with a space."

The idea is to test to make sure the first character in the string received for the given name is not a space and return an error-echo if it is. It'll then repeat the loop, so the user is given another opportunity to get it right. In theory this continues until a valid given name is received.

However, it doesn't work this way. Instead, this code is skipped over. Spaces are truncated from entries with a leading space anyway - but the problem is, I'm using this same code to collect job title information. Job titles often have spaces in them (though not at the start.)

The expr continues to fail at picking up leading spaces - but, more strangely, if there is a space somewhere else in the string, expr encounters a syntax error, and the echo displays that a job title may not begin with a space.

Any suggestions on how I could detect leading spaces and produce an error, while still allowing spaces elsewhere in the string?

Thanks in advance for help,
Wolfie
You can try something like :
Code:
echo "$var" | grep -q '^ '


Output:
Quote:
/home/ans >x=' zxc'
/home/ans >echo "$x"
zxc
/home/ans >echo "$x" | grep '^ '
zxc
/home/ans >x="fds"
/home/ans >echo "$x" | grep '^ '
/home/ans >
# 3  
Old 09-03-2008
Hi Dennis, I see where you're going with your suggestion, and I tried it out.

It's still not reporting the error for the leading space. There are less errors now if I feed it a string with spaces in other places, but it's still complaining that the elif has been fed too many arguments.

Any other ideas?
# 4  
Old 09-03-2008
Code:
$ cat s
#! /bin/bash

printf 'enter name: '
while IFS= :; do
  read
  case $REPLY in
    \ *) printf 'invalid, retry: ';;
      *) printf 'ok\n';break;;
  esac
done
$ ./s
enter name:  initial space
invalid, retry: no_space
ok


Last edited by radoulov; 09-03-2008 at 07:42 AM.. Reason: depending on your shell, you may need to modify the IFS temporarily
# 5  
Old 09-03-2008
My God, Dennis, that's overkill.

Silentwolf, you're on the right track -- but the if statement won't work without double-quoting the space on the left-side. And then it won't work because the expansion of g_name results in a space gobbled up by the parser before finding its way to expr. Just prefix the expression with a character and get the 2nd character.

Code:
elif [ "`expr substr X$g_name 2 1`" = " " ] ; then
                                                echo "Given name may not begin with a space."

But I think there is a simpler way:

Code:
elif [ "`echo $g_name`" = "$g_name" ] ; then
                                                echo "Given name may not begin with a space."

HOWEVER, that will fail if the name contains MULTIPLE spaces or trails with a space (the echo command will seemingly "compress" each into one space and cut off the ending spaces).

Finally, if using ksh or bash, you can use the ${#%} operators, such as this:
Code:
elif [ " ${g_name# }" = "$g_name" ] ; then
                                                echo "Given name may not begin with a space."

This strips the leading space of g_name if it's there, then prefixes the space to g_name. If that is different than $g_name, it means the strip failed. There are other ways to do this, like:

Code:
elif [ "${g_name# }" != "$gname" ] ; then
                                                echo "Given name may not begin with a space."

OR

Code:
elif [ "${g_name%% *}" = "" ] ; then
                                                echo "Given name may not begin with a space."

Which is the reverse -- you cut everything after the space, including the space, and if the resulting string is empty, the cut succeeded and started with the first character of the string, ie, the first character was blank.
# 6  
Old 09-03-2008
The problem is that most shells will strip leading and trailing IFS characters, so you need to modify the IFS value(s) temporarily (see my post above).

Last edited by radoulov; 09-03-2008 at 07:51 AM..
# 7  
Old 09-03-2008
I should have mentioned, I'm working in the Bourne shell, sh. So some of the suggestions won't work.

Because I'm lazy I tried doing the 'character in front and then get the second character' solution, but it didn't make a difference, lol.

I'm now trying some of the other suggestions, I'll report back shortly.
Login or Register to Ask a Question

Previous Thread | Next Thread

9 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

C shell concatenate string doesn't work

I have the following code: #!/bin/csh clear set cloud_file="/home/labs/koren/davidsr/general_scripts/MFP_10_PP_Parmas.txt" # to fill set mie_tables_dir='/home/labs/koren/davidsr/SHDOM_MAIN/MIE_TABLES/non_polo_wave_0.7_water_50R_s0.5_e25_max_70.mie' # to fill set prp_dir='${pp_dir}/pp_prp/'... (2 Replies)
Discussion started by: student_wiz
2 Replies

2. UNIX for Beginners Questions & Answers

Delete Directories and its files that begin with the same character string

I wrote a shell script program that supposed to delete any directories and its files that begin with the same character string . The program is designed to delete directories and its files that are one day old or less and only the directories that begin with the same character string. The problem... (1 Reply)
Discussion started by: dellanicholson
1 Replies

3. Shell Programming and Scripting

Ensuring certain processes do not show up in process table

i've read somewhere a long time ago that there's a way to hide the workings of a script in sub functions so that when run, it doesn't show up in the process table. is this really possible? for instance, i need to run a command that has a password in it. and when that;s being run, it can be... (2 Replies)
Discussion started by: SkySmart
2 Replies

4. Shell Programming and Scripting

How to test that a string doesn't contain specific characters?

Hi ! :) I made this : #!/bin/bash rsa_dir="/etc/openvpn/easy-rsa/" rsa_key_dir="/etc/openvpn/easy-rsa/keys/" ccd_dir="/etc/openvpn/ccd/" regex_special_char='' cd $rsa_dir while read -p "Please can you enter the vpn's username : " username ] || ] || ] || ] do echo "Your entry... (10 Replies)
Discussion started by: Arnaudh78
10 Replies

5. Shell Programming and Scripting

Inserting new line if two sequential lines begin with the same string

Hi I have a file like this: Peter North Mary Peter North Peter Borough Mary I need there to put 'X' (or anything) on a new line between the two lines where 'Peter' begins the line. There will be many matches to this string, but they will always begin with 'Peter'. Ie, the resulting... (2 Replies)
Discussion started by: majormajormajor
2 Replies

6. UNIX for Dummies Questions & Answers

Ensuring / at end of directory path

I have a variable name storing a directory path set dirpath = /home/chrisd/tatsh/branches/terr0.50/darwin I want to ensure there is always a "/" at the end, and if there are more than one "/", that I reduce it to just one. ---------- Post updated at 08:16 AM ---------- Previous update was... (3 Replies)
Discussion started by: kristinu
3 Replies

7. Shell Programming and Scripting

Check whether a string begin with uppercase, lowercase or digit!

Hi every body! I wrote script on Fedora (bash shell) to check whether a tring enter from user console is start with a uppercase/lowercase letter or a digit. But with this script i have some problem when I enter from character from 'b' to 'z' --> result is uppercase. This code look like ok but i... (9 Replies)
Discussion started by: nguyendu0102
9 Replies

8. Shell Programming and Scripting

Replace string with sed doesn't work

Hello, Unfortunately I don't found any working solution for my problem :/ I have pass file for dovecot authorizing in this format: user@domain.tld:{SSHA}Ykx2KVG/a2FKzjnctFFC2qFnrk9nvRmW:5000:5000:::: . . ...Now, I want to write some sh script for password changing for grep'ed user, in... (5 Replies)
Discussion started by: vincenty
5 Replies

9. Shell Programming and Scripting

awk BEGIN END and string matching problem

Hi, Contents of BBS-list file: foo foo foo awk ' BEGIN { print "Analysis of \"foo\"" } /foo/ { ++n } END { print "\"foo\" appears", n, "times." }' BBS-list Output: Analysis of "foo" "foo" appears 3 times. awk ' (3 Replies)
Discussion started by: cola
3 Replies
Login or Register to Ask a Question