简体   繁体   English

在脚本中使用 grep

[英]Using grep inside a script

I'm trying to search a file to find a word using grep.我正在尝试使用 grep 搜索文件以查找单词。 I'm trying to use it inside of a script but I am unable to get it to work.我试图在脚本中使用它,但我无法让它工作。 I'm a beginner at this so my code is probably not good.我是这方面的初学者,所以我的代码可能不好。 Here's what I have so far这是我到目前为止所拥有的

#!/bin/bash
echo "apple", "book", "cat" >> file.txt

read -r filename
filename='file.txt'
"$4"=filename
"$1"=grep
"$2"=-R

So ideally I want the user to be able to type the name of the script on the command line along with the word they are searching for, which in this case would be "book".所以理想情况下,我希望用户能够在命令行上键入脚本的名称以及他们正在搜索的单词,在本例中为“book”。

user:~/dir$ ./wordfind.sh book

I may be doing this completely wrong, but when I run the above in the command line, it freezes and I have to Ctrl-Z to get out of it.我可能完全错误地这样做,但是当我在命令行中运行上述命令时,它会冻结,我必须按 Ctrl-Z 才能摆脱它。 Thanks.谢谢。

The question is not clear enough.问题不够清楚。

This answer assumes that you want to call your script with a string or regex as the first argument, ie the search term must be quoted if it contains spaces or special characters.此答案假定您希望使用字符串或正则表达式作为第一个参数来调用脚本,即如果搜索词包含空格或特殊字符,则必须引用它。

You could change the script wordfind.sh to您可以将脚本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

Examples:例子:

$ ./wordfind.sh rice
out, owl, rice

$ ./wordfind.sh 'z.*a'
say, toy, zebra

$ ./wordfind.sh 'd, f'
dad, food, girl

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM