views:

44

answers:

4

hi I write the following syntax (part of my ksh script) to check if the first word of LINE=star and the second word is car

     [[ ` echo $LINE | awk '{print $1}' ` = star  ]] && [[  ` echo $LINE | awk '{print $2}' ` = car  ]] && print "match"

I need other simple smart and shorter solution then my syntax. from awk,perl or sed(if it possible to use echo only once or better if we cant not use echo, because I need to save time to minimum) can I get some ideas?

A: 

You can do:

[[ ` echo $LINE | awk '{printf("%s:%s",$1,$2)}'` = star:car ]] && print "match"
codaddict
@codaddict: same problem as [ghostdog74](http://stackoverflow.com/questions/3563349/ksh-smart-test-line-solution/3563752#3563752), plus calling awk contradicts the speed requirement in the question.
Gilles
+1  A: 

You don't need an external process at all:

[[ $LINE == *([ ])star+([ ])car?([ ]*) ]]

If you also need to extract the first word sometimes (warning, typed directly into the browser):

LINE=${LINE##+[ ]}  # strip leading spaces
first_word=${LINE%%[ ]*}
if [[ $LINE = *[ ]* ]]; then
  LINE_minus_first_word=${LINE##*+([ ])}
else
  LINE_minus_first_word=''
fi

Add a tab inside the brackets if they may appear in $LINE.

Gilles
You should mention that these require `shopt -s extglob`.
Dennis Williamson
I should have said "...for Bash" since they are always on for ksh.
Dennis Williamson
+1  A: 

you don't actually need to call any external tools

set -f 
set -- $LINE
case "$1 $2" in 
 "star car") 
    echo "match";;
esac
ghostdog74
@ghostdog74: This will sometimes match when it shouldn't, e.g., with `LINE='star *'`. It would work if you did `set -f` first, to turn off glob expansion on the unquoted substitution of `$LINE` (and even that is fragile if you change the searched strings, because some backslashes are always expanded in unquoted substitutions).
Gilles
+1  A: 
set -o noglob
words=($LINE)
[[ "${words[0]} ${words[1]}" == "star car" ]] && print "match"

Edit:

Using ksh and Bash's regex matching (Bash >= version 3.2):

pattern='^[[:blank:]]*star[[:blank:]]+car([[:blank:]]+|$)'
[[ $LINE =~ $pattern ]] && print "match"
Dennis Williamson