Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
bash读取输入(1个必填和1个可选)和grep这两个变量,然后重定向结果_Bash_Shell_Input_Grep_Arguments - Fatal编程技术网

bash读取输入(1个必填和1个可选)和grep这两个变量,然后重定向结果

bash读取输入(1个必填和1个可选)和grep这两个变量,然后重定向结果,bash,shell,input,grep,arguments,Bash,Shell,Input,Grep,Arguments,读取输入(1个强制输入和1个可选输入) 并从abc.txt 然后将结果重定向到新的txt read c d while [ $# -ne 1 ]; do #why -ne not -ge as grep c when there is at least 1 argument echo "Search result :" grep "$c" abc.txt else grep "$c" "$d" abc.txt break done 尝试了很多次,要么将c

读取输入(1个强制输入和1个可选输入)

并从
abc.txt
然后将结果重定向到新的txt

read c d

while [ $# -ne 1 ]; do    #why -ne not -ge as grep c when there is at least 1 argument
        echo "Search result :"
        grep "$c" abc.txt
else grep "$c" "$d" abc.txt
break
done
尝试了很多次,要么将
c
d
作为一个参数,要么忽略我的
d
参数。在这种情况下是否需要使用shift?

$#
是shell脚本的命令行参数数<代码>读取不会更改此值

你想要的是:

if [[ -z "$d" ]]; then
    # one argument
else 
    # two or more arguments
fi
或者,使用命令行上的参数调用脚本(即
/script cd
)。 为此,将
读取CD
替换为:

c="$1"
shift
d="$*"

您可以使用
${d+value\u if\u set}
来填写一个值,以便在出现
$d
时使用

grep -e "$c" ${d+-e "$d"} abc.txt >new.txt
如果设置了
$d
,则在第一个参数之后添加第二个
-e
参数。因此,在这个场景中,您将运行
grep-e“$c”-e“$d”abc.txt

我(很久以前)读过一些建议,反对在
grep
中使用多个
-e
参数,但它至少可以与GNU
grep
和OSX(*BSD)
grep
一起使用

或者,您可以使用
grep-E
并修改正则表达式:

grep -E "$c${d+|$d}" abc.txt >new.txt

这里,正则表达式是
$c
$c |$d
。但是您应该注意到,
-E
语法也会更改您在
$c
$d
中所输入内容的语义欢迎使用SO!请花些时间重写你的问题,使其有意义,并做一些格式化。