简体   繁体   English

linux脚本查找文件名中的特定单词

[英]linux script to find specific words in file names

I need help writing a script to do the following stated below in part a. 我需要编写脚本来完成下面a部分所述的操作。

The following code will output all of the words found in $filename, each word on a separate line. 以下代码将输出在$ filename中找到的所有单词,每个单词在单独的行中。

for word in “cat $filename”
do
    echo $word
done 

a. 一种。 Write a new script which receives two parameters. 编写一个接收两个参数的新脚本。 The first is a file's name ($1 instead of $filename) and the second is a word you want to search for ($2). 第一个是文件名($ 1代替$ filename),第二个是您要搜索的单词($ 2)。 Inside the for loop, instead of echo $word, use an if statement to compare $2 to $word. 在for循环内,而不是echo $ word,请使用if语句将$ 2与$ word进行比较。 If they are equal, add one to a variable called COUNT. 如果它们相等,则将一个加到一个称为COUNT的变量中。 Before the for loop, initialize COUNT to 0 and after the for loop, output a message that tells the user how many times $2 appeared in $1. 在for循环之前,将COUNT初始化为0,在for循环之后,输出一条消息,告诉用户$ 2在$ 1中出现了多少次。 That is, output $COUNT, $2 and $1 in an echo statement but make sure you have some literal words in here so that the output actually makes sense to the user. 也就是说,在echo语句中输出$ COUNT,$ 2和$ 1,但请确保此处包含一些文字,这样输出对用户才有意义。 HINTS: to compare two strings, use the notation [ $string1 == $string2 ]. 提示:要比较两个字符串,请使用符号[$ string1 == $ string2]。 To add one to a variable, use the notation X=$((X+1)). 要将X加到变量中,请使用符号X = $((X + 1))。 If every instruction is on a separate line, you do not need any semicolons. 如果每条指令都在单独的行上,则不需要任何分号。 Test your script on /etc/fstab with the word defaults (7 occurrences should be found) 使用默认值一词在/ etc / fstab上测试您的脚本(应该发现7次)

This is what I got so far, but it does not work right. 这是我到目前为止所得到的,但是它不能正常工作。 It says it finds 0 occurrences of the word "defaults" in /etc/fstab. 它说在/ etc / fstab中找到0个单词“ defaults”。 I am sure my code is wrong but can't figure out the problem. 我确定我的代码是错误的,但无法找出问题所在。 Help is appreciated. 感谢帮助。

count=0
echo “what word do you want to search for?: “
read two
for word in “cat $1”
do
    if [ “$two” == “$word” ]; then
        count=$((count+1))
    fi
done
echo $two appeared $count times in $1

You need to use command substitution, you were looping over this string: cat first_parameter . 您需要使用命令替换,您正在遍历以下字符串: cat first_parameter

for word in $(cat "$1")

Better way to do this using grep , paraphrasing How do I count the number of occurrences of a word in a text file with the command line? 更好的方法是使用grep解释, 如何用命令行计算单词在文本文件中出现的次数?

grep -o "\<$two\>" "$1" | wc -l

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

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