我正在尝试使用grep搜索文件以查找单词。我试图在脚本中使用它,但我无法使它发挥作用。我是这方面的初学者,所以我的代码可能不好。以下是我目前拥有的
#!/bin/bash
echo "apple", "book", "cat" >> file.txt
read -r filename
filename='file.txt'
"$4"=filename
"$1"=grep
"$2"=-R
因此,理想情况下,我希望用户能够在命令行上键入脚本的名称以及他们正在搜索的单词,在这种情况下,该单词将是";书";。
user:~/dir$ ./wordfind.sh book
我可能做得完全错了,但当我在命令行中运行上述操作时,它会冻结,我必须按Ctrl-Z才能退出。谢谢。
这个问题还不够清楚。
这个答案假设您想用字符串或正则表达式作为第一个参数来调用脚本,即如果搜索项包含空格或特殊字符,则必须引用该搜索项。
您可以将脚本wordfind.sh
更改为
#!/bin/bash
# note: I changed >> to > here to avoid duplicating the data on repeated calls
echo "apple", "book", "cat" > file.txt
echo "dad", "food", "girl" >> file.txt
echo "god", "hey", "linux" >> file.txt
echo "out", "owl", "rice" >> file.txt
echo "say", "toy", "zebra" >> file.txt
# Check if exactly one argument was specified.
if [ $# -ne 1 ]
then
echo "usage: $0 'regex'"
exit 1
fi
grep "$1" file.txt
示例:
$ ./wordfind.sh rice
out, owl, rice
$ ./wordfind.sh 'z.*a'
say, toy, zebra
$ ./wordfind.sh 'd, f'
dad, food, girl