LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   checking whitespaces in a string (https://www.linuxquestions.org/questions/linux-newbie-8/checking-whitespaces-in-a-string-4175474881/)

omkar.jadhav 08-27-2013 08:28 AM

checking whitespaces in a string
 
i want to create a shell script which will take string (for eg: om-23%)as a user input and identifies in case that string contains any spaces (begining/in between characters/end/combination of all of these) of the string

pan64 08-27-2013 08:30 AM

yes, do you have a plan or a test version?

omkar.jadhav 08-27-2013 08:36 AM

i have created and tried the below loops but they all failes to detect spaces present at the end of the given string(for eg : om-23%<space><space> )
1. if [ "$string" != "${string% *}" ]; then
echo "$string contains one or more spaces";
fi
2. if ( echo "$string" | grep -q ' ' ); then
echo 'string contains one or more spaces'
exit 1
fi

pan64 08-27-2013 08:41 AM

actually those spaces are ignored, you can check:
Code:

read a; echo "XX${a}YY"
> a d f g h j k            <-- spaces at the end
result:
XXa d f g h j kYY

so grep will not be able to find those trailing whitespace(s).


All times are GMT -5. The time now is 02:53 AM.