【问题标题】:shell test operator regular expressionsshell 测试运算符正则表达式
【发布时间】:2012-08-21 22:44:37
【问题描述】:
#!/bin/bash
# This file will fix the cygwin vs linux paths and load programmer's notepad under windows.
# mail : <sandundhammikaperera@gmail.com> 
# invokes the GNU GPL, all rights are granted.


# check first parameter is non empty.
# if empty then give a error message and exit.
file=${1:?"Usage: pn filename"};

if [[ "$file" == /*/* ]] ;then
  #if long directory name.
# :FAILTHROUGH:
  echo "$0: Executing pn.exe $file" 

else 
  file="$(pwd)/$file";
fi

#check whether the filename starts with / if so replace it with appropriate prefix #
prefix="C:/cygwin/";

#check for the partterns starting with "/" #
echo $var | grep "^/*$"
if [[ "$?" -eq "0" ]] ;then
  # check again whether parttern starts with /cygdrive/[a-z]/ parttern #
  if [[ $file == /cygdrive/[a-z]/* ]] ; then 
    file=${file#/cygdrive/[a-z]/};
    file="C:/"$file;
  else
    file="$prefix""$file";  
  fi 
fi


#check for the appropriate file permissions #
# :TODO: 


echo $file
exec "/cygdrive/c/Program Files (x86)/Programmer's Notepad/pn.exe"  $file 

正如我在我的程序中转换 cygwin 和 windows 之间的路径名并加载 pn.exe [Windows 中的程序员记事本]。所以我的问题是,

  1. “[[”或“test”运算符内置了正则表达式。 (也 我在上面的程序中使用了它们)。但是,如果我改变了,为什么它们不能在这里工作,

    echo $var | grep "^/*$"
    if [[ "$?" -eq "0" ]] ;then
    

    到这里,

    if [[ "$file" == ^/*$ ]] ;then
    

    这是什么原因?有什么解决方法吗? 我已经尝试过第二种方法[[ "$file" == ^/*$ ]],但没有奏效。 然后,简单的谷歌搜索给我带来了这里:http://unix.com/shell-programming

  2. 如何找到所有关于 [[ operator 或 'test' 命令的文档?我用过了 man test 但是:(。如果有的话,哪个文档指定了它对正则表达式使用的限制。

【问题讨论】:

标签: regex shell


【解决方案1】:

首先,grep "^/*$" 将仅匹配仅包含斜杠的路径,例如“/”、“///”、“////”。您可以使用grep "^/" 匹配以斜杠开头的路径。如果你想使用 bash 正则表达式:

var="/some"
#echo $var | grep "^/"
if [[ "$var" =~ ^/ ]] ;then
  echo "yes"
fi

【讨论】:

猜你喜欢
  • 2012-10-30
  • 2013-10-26
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-03
  • 2016-10-20
相关资源
最近更新 更多