0

我正在做一个编程任务,我必须在文本文件中搜索一个条目,并打印出与该条目对应的文本。例如,假设我有一个条目如下,

约翰·多伊

34 正确的方式

哈利法克斯

465-0394

,并且用户输入 HALIFAX 作为关键字,然后我想找到 Halifax 所在的行,然后打印出与该条目相关的所有文本。棘手的部分是在没有 grep、sed 或 awk 的情况下完成这一切,因为如果使用这些命令,则不接受分配。我考虑过使用正则表达式,但这些文本操作只能在一行中完成,而且我必须对整个文件进行操作。到目前为止,我很困惑,任何帮助将不胜感激!

亚历克斯

4

3 回答 3

1

您应该逐行阅读 bash 脚本中的整个文件,然后检查该行是否包含您的搜索词

cat $FILENAME | while read LINE
do
       if [[ $LINE =~ *HALIFAX* ]] then
          echo "I found HALIFAX"
       fi
done

从这里开始,您应该很容易打印出其余部分。

于 2013-07-12T02:24:10.717 回答
0

I'm assuming this is bash scripting from the tag. My suggestion would be to read the text file line by line into an array, and then loop through the array, searching for the keyword in each string. This can be done using wild cards. Here's a link: String contains in Bash. Could you clarify "print out all associated text with this entry"?

于 2013-07-12T02:18:13.887 回答
0

您可以通过使用 while 循环逐行读取文件来做到这一点。

#set the delimiter to newline
IFS_backup=$IFS
IFS=$'\n'

#variable to calculate line number
lineNum=0
while read a1
do
let "lineNum++" #increment variable for each line 

#variable a1 store the value of each line 

#do comparision with $a1 by user input string
#if string match then value of lineNum equal to the line number of file
# containing user input string

done<filename
于 2013-07-12T02:24:38.260 回答