Unix命令在文件中查找单词

Unix命令在文件中查找单词

我们有一个 shell 脚本。在shell脚本中,我们想要找出文件中是否file.log有word as MB.如果是,则将其存储到 shell 脚本中的变量中v_name,如果不存在该单词,则应v_name为空。

笔记:file.log遗嘱最多包含一个MB单词。

答案1

如果file.log包含字符串MB,则将文本分配MB给变量v_name

grep -q MB file.log && v_name=MB

参考:手册页对于 grep

答案2

在文件中查找单词的 unix 命令是

grep

$ man grep | grep -A 5 DESCRIPTION
DESCRIPTION
   grep  searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a
   match to the given PATTERN.  By default, grep prints the matching lines.

   In addition, three variant programs egrep, fgrep and rgrep are available.  egrep is the same as grep -E.  fgrep is the same as grep -F.  rgrep is  the  same
   as grep -r.  Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified.

答案3

v_name=$(grep -P "\d+\.\d+ MB")

给出您的变量,例如“92.29 MB”

答案4

#!/bin/bash

# $1 = pattern
# $2 = file name to search in
# did not write or test script to handle wild cards in $2

# -i option in grep is case insensitive, use just -l if you care about case

vname=`grep -li $1 $2`

if [ -z "$vname" ]; then
   echo "vname is empty"
else
   echo "vname is " $vname
   # set vname to pattern searched for
   vname=$1
   echo "vname is " $vname
fi

相关内容