LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 758|回复: 10

一个很简单的匹配字符串的问题, 但是很急...

[复制链接]
发表于 2005-10-11 14:18:04 | 显示全部楼层 |阅读模式
在ksh中如何实现下面的代码呢?

if [  字符串以"-"开头 ]; then
    echo "true"
else
    echo "false"
fi

如何实现呢?
发表于 2005-10-11 14:30:33 | 显示全部楼层
if echo $string | grep -q ^\- ; then
echo true
else
echo false
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-10-11 14:36:00 | 显示全部楼层
试过,不行,我的系统是solaris, 没有grep -q选项
回复 支持 反对

使用道具 举报

发表于 2005-10-11 14:49:46 | 显示全部楼层
grep 不是内建命令,和shell无关,solaris用/usr/xpg4/bin/grep
回复 支持 反对

使用道具 举报

发表于 2005-10-11 14:56:37 | 显示全部楼层

  1. str=xxx
  2. awk 'BEGIN{print('"$str"'~/^-/)?"true":"false"}'
复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-10-11 15:14:39 | 显示全部楼层
谢谢各位,可惜都不能用啊
回复 支持 反对

使用道具 举报

发表于 2005-10-11 15:16:23 | 显示全部楼层
到底是哪里有问题,什么版本的grep,索性装个gnu grep
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-10-11 15:20:02 | 显示全部楼层
我只能用/bin/grep,不能随便装软件
回复 支持 反对

使用道具 举报

发表于 2005-10-11 15:42:09 | 显示全部楼层
use perl :
code:
richard:/home/richard/shellcode# cat test.pl
#/usr/bin/perl
print "please type some character string to test:";
$str=<STDIN>;
chop($str);
if ($str =~ /^-/) {
print "ture\n";
} else {
print "false\n";
}
richard:/home/richard/shellcode# perl test.pl
please type some character string to test:aaa
false
richard:/home/richard/shellcode# perl test.pl
please type some character string to test:-aaa
ture
richard:/home/richard/shellcode#
回复 支持 反对

使用道具 举报

发表于 2005-10-11 16:00:30 | 显示全部楼层
use perl:

  1. str=xxx
  2. echo $str|perl -ne 'if(/^-/){print "ok"}else{print "no"}'
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表