How to check for whitespace characters using sed or grep in shell script?

I tried this, but it doesn't work.

if [ $char -eq " " -o $char -eq "" -o $char -eq "   " ]

Upvotes: 3

Views: 2514

Answers (4)

kyodev
kyodev

Reputation: 583

-eq for numeric value, for string, use ==

if [[ $char == " " || -z $char || $char == "   " ]]; then
  • -z equivalent ""
  • || equivalent -o

regex alternative with recent bash ( 0 or 1 space or 3 spaces ):

if [[ $char =~ ^\ {0,1}$ || $char =~ ^\ {3}$ ]] ; then
  • \ : space only
  • [[:blank:]] : space, tab
  • [[:space:]] : space, tab, newline, vertical tab, form feed, carriage return
  • if you want to match 0 to 3 spaces: if [[ $char =~ ^\ {0,3}$ ]] ; then

Upvotes: 1

123
123

Reputation: 11216

In bash you can use regex match in [[]]

if  [[ $char =~ [[:space:]] ]]

If you actually want to match a single whitespace character

if  [[ $char =~ ^[[:space:]]$ ]]

Or single whitespace or nothing

if  [[ $char =~ ^[[:space:]]?$ ]]

Or only whitespace in a string

if  [[ $char =~ ^[[:space:]]+$ ]]

Or only whitespace or nothing

if  [[ $char =~ ^[[:space:]]*$ ]]

Upvotes: 0

Sakis
Sakis

Reputation: 91

This works for single char variable $char, but note that the post assumes mainly a multi-char variable.

Use:

if grep -q '\s' <<< "$char"; then ...

Upvotes: 1

Thaw
Thaw

Reputation: 861

-eq is for numerics. Also, you should enclose the variable in quotes, such as "$char", not $char

#! /bin/sh

A=1
B=" "

if [ "$A" -eq 1 ]; then
    echo "eq is for numeric"
fi

if [ "$B" = " " ]; then
    echo "= is for characters"
fi

Upvotes: 1

Related Questions