我正在编写一个bash脚本,使用GREP在文件中搜索模式.我无法解释为什么它不起作用.这是该计划
echo "Enter file name...";
read fname;
echo "Enter the search pattern";
read pattern
if [ -f $fname ]; then
result=`grep -i '$pattern' $fname`
echo $result;
fi
Run Code Online (Sandbox Code Playgroud)
或者有不同的方法来做到这一点?
谢谢
(文件内容)
Welcome to UNIX
The shell is a command programming language that provides an interface to the UNIX operating system.
The shell can modify the environment in which commands run.
Simple UNIX commands consist of one or more words separated by blanks.
Most commands produce output on the standard output that is initially connected to the terminal. This output may be sent to a file by writing.
The standard output of one UNIX command may be connected to the standard input of another UNIX Command by writing the `pipe' operator, indicated by |
Run Code Online (Sandbox Code Playgroud)
(图案)
`UNIX` or `unix`
Run Code Online (Sandbox Code Playgroud)
这些分号中只有一个是必需的(之前的那个then),但我通常会省略它并单独放在then一行。您应该在要回显的变量周围和保存grep模式的变量周围加上双引号。保存文件名的变量也应该被引用。您可以read显示您的提示。您应该使用$()而不是反引号。
read -p "Enter file name..." fname
read -p "Enter the search pattern" pattern
if [ -f "$fname" ]
then
result=$(grep -i "$pattern" "$fname")
echo "$result"
fi
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72819 次 |
| 最近记录: |