检查文件是否存在,是否包含特定的字符串

时间:2022-03-08 07:15:32

I want to check if file2.sh exists and also if a specific word, poet is part of the file. I use grep to create the variable used_var.

我想查一下文件2。sh的存在,如果一个特定的词,诗人是文件的一部分。我使用grep创建变量used_var。

#!/bin/kshfile_name=/home/file2.sh                  used_var=`grep "poet" $file_name`    

How can I check if used_var has some value?

如何检查used_var是否有一些值?

5 个解决方案

#1


46  

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

与其将grep的输出存储在一个变量中,然后检查变量是否为空,不如这样做:

if grep -q "poet" $file_namethen    echo "poet was found in $file_name"fi

============

= = = = = = = = = = = =

Here are some commonly used tests:

以下是一些常用的测试:

   -d FILE          FILE exists and is a directory   -e FILE          FILE exists   -f FILE          FILE exists and is a regular file   -h FILE          FILE exists and is a symbolic link (same as -L)   -r FILE          FILE exists and is readable   -s FILE          FILE exists and has a size greater than zero   -w FILE          FILE exists and is writable   -x FILE          FILE exists and is executable   -z STRING          the length of STRING is zero

Example:

例子:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]then    echo "$file_name exists and $used_var is not empty"fi

#2


12  

if test -e "$file_name";then ...fiif grep -q "poet" $file_name; then  ..fi

#3


6  

test -e will test whether a file exists or not. The test command returns a zero value if the test succeeds or 1 otherwise.

test -e将测试文件是否存在。如果测试成功,则test命令返回0,否则返回1。

Test can be written either as test -e or using []

测试可以写为Test -e或使用[]

[ -e "$file_name" ] && grep "poet" $file_name

Unless you actually need the output of grep you can test the return value as grep will return 1 if there are no matches and zero if there are any.

除非您实际需要grep的输出,否则可以测试返回值,因为如果没有匹配,grep将返回1,如果有匹配,返回0。

In general terms you can test if a string is non-empty using [ "string" ] which will return 0 if non-empty and 1 if empty

一般来说,您可以使用["string"]测试一个字符串是否为非空,如果为空,则返回0,如果为空,则返回1

#4


4  

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

如果您已经安装了测试二进制文件,或者ksh有一个匹配的内置函数,您可以使用它来执行检查。通常/bin/[是测试的符号链接:

if [ -e "$file_name" ]; then  echo "File exists"fiif [ -z "$used_var" ]; then  echo "Variable is empty"fi

#5


1  

You should use the grep -q flag for quiet output. See the man pages below:

您应该使用grep -q标志进行安静输出。参见下面的手册页:

man grep output :

男人grep输出:

 General Output Control  -q, --quiet, --silent              Quiet;  do  not write anything to standard output.  Exit immediately with zero status              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

这个KornShell (ksh)脚本演示了grep的静态输出,并解决了您的问题。

grepUtil.ksh :

grepUtil。ksh:

#!/bin/ksh#Initialize Variablesfile=poet.txtvar=""dir=tempDirdirPath="/"${dir}"/"searchString="poet"#Function to initialize variablesinitialize(){    echo "Entering initialize"    echo "Exiting initialize"}#Function to create File with Input#Params: 1}Directory 2}File 3}String to write to FileNamecreateFileWithInput(){    echo "Entering createFileWithInput"    orgDirectory=${PWD}    cd ${1}    > ${2}    print ${3} >> ${2}    cd ${orgDirectory}    echo "Exiting createFileWithInput"}#Function to create File with Input#Params: 1}directoryNamecreateDir(){    echo "Entering createDir"    mkdir -p ${1}    echo "Exiting createDir"}#Params: 1}FileNamereadLine(){    echo "Entering readLine"    file=${1}    while read line    do        #assign last line to var        var="$line"    done <"$file"    echo "Exiting readLine"}#Check if file exists #Params: 1}FiledoesFileExit(){    echo "Entering doesFileExit"    orgDirectory=${PWD}    cd ${PWD}${dirPath}    #echo ${PWD}    if [[ -e "${1}" ]]; then        echo "${1} exists"    else        echo "${1} does not exist"    fi    cd ${orgDirectory}    echo "Exiting doesFileExit"}#Check if file contains a string quietly#Params: 1}Directory Path 2}File 3}String to seach for in FiledoesFileContainStringQuiet(){    echo "Entering doesFileContainStringQuiet"    orgDirectory=${PWD}    cd ${PWD}${1}    #echo ${PWD}    grep -q ${3} ${2}    if [ ${?} -eq 0 ];then        echo "${3} found in ${2}"    else        echo "${3} not found in ${2}"    fi    cd ${orgDirectory}    echo "Exiting doesFileContainStringQuiet"}#Check if file contains a string with output#Params: 1}Directory Path 2}File 3}String to seach for in FiledoesFileContainString(){    echo "Entering doesFileContainString"    orgDirectory=${PWD}    cd ${PWD}${1}    #echo ${PWD}    grep ${3} ${2}    if [ ${?} -eq 0 ];then        echo "${3} found in ${2}"    else        echo "${3} not found in ${2}"    fi    cd ${orgDirectory}    echo "Exiting doesFileContainString"}#-----------#---Main----#-----------echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"#initialize #function call#createDir ${dir} #function call#createFileWithInput ${dir} ${file} ${searchString} #function call#doesFileExit ${file} #function call#if [ ${?} -eq 0 ];then    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#    doesFileContainString ${dirPath} ${file} ${searchString} #function call#fiecho "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

grepUtil。ksh输出:

user@foo /tmp$ ksh grepUtil.kshStarting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:Entering createDirExiting createDirEntering createFileWithInputExiting createFileWithInputEntering doesFileExitpoet.txt existsExiting doesFileExitEntering doesFileContainStringQuietpoet found in poet.txtExiting doesFileContainStringQuietEntering doesFileContainStringpoetpoet found in poet.txtExiting doesFileContainStringExiting: /tmp/grepUtil.ksh

#1


46  

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

与其将grep的输出存储在一个变量中,然后检查变量是否为空,不如这样做:

if grep -q "poet" $file_namethen    echo "poet was found in $file_name"fi

============

= = = = = = = = = = = =

Here are some commonly used tests:

以下是一些常用的测试:

   -d FILE          FILE exists and is a directory   -e FILE          FILE exists   -f FILE          FILE exists and is a regular file   -h FILE          FILE exists and is a symbolic link (same as -L)   -r FILE          FILE exists and is readable   -s FILE          FILE exists and has a size greater than zero   -w FILE          FILE exists and is writable   -x FILE          FILE exists and is executable   -z STRING          the length of STRING is zero

Example:

例子:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]then    echo "$file_name exists and $used_var is not empty"fi

#2


12  

if test -e "$file_name";then ...fiif grep -q "poet" $file_name; then  ..fi

#3


6  

test -e will test whether a file exists or not. The test command returns a zero value if the test succeeds or 1 otherwise.

test -e将测试文件是否存在。如果测试成功,则test命令返回0,否则返回1。

Test can be written either as test -e or using []

测试可以写为Test -e或使用[]

[ -e "$file_name" ] && grep "poet" $file_name

Unless you actually need the output of grep you can test the return value as grep will return 1 if there are no matches and zero if there are any.

除非您实际需要grep的输出,否则可以测试返回值,因为如果没有匹配,grep将返回1,如果有匹配,返回0。

In general terms you can test if a string is non-empty using [ "string" ] which will return 0 if non-empty and 1 if empty

一般来说,您可以使用["string"]测试一个字符串是否为非空,如果为空,则返回0,如果为空,则返回1

#4


4  

If you have the test binary installed or ksh has a matching built-in function, you could use it to perform your checks. Usually /bin/[ is a symbolic link to test:

如果您已经安装了测试二进制文件,或者ksh有一个匹配的内置函数,您可以使用它来执行检查。通常/bin/[是测试的符号链接:

if [ -e "$file_name" ]; then  echo "File exists"fiif [ -z "$used_var" ]; then  echo "Variable is empty"fi

#5


1  

You should use the grep -q flag for quiet output. See the man pages below:

您应该使用grep -q标志进行安静输出。参见下面的手册页:

man grep output :

男人grep输出:

 General Output Control  -q, --quiet, --silent              Quiet;  do  not write anything to standard output.  Exit immediately with zero status              if any match is  found,  even  if  an  error  was  detected.   Also  see  the  -s  or              --no-messages option.  (-q is specified by POSIX.)

This KornShell (ksh) script demos the grep quiet output and is a solution to your question.

这个KornShell (ksh)脚本演示了grep的静态输出,并解决了您的问题。

grepUtil.ksh :

grepUtil。ksh:

#!/bin/ksh#Initialize Variablesfile=poet.txtvar=""dir=tempDirdirPath="/"${dir}"/"searchString="poet"#Function to initialize variablesinitialize(){    echo "Entering initialize"    echo "Exiting initialize"}#Function to create File with Input#Params: 1}Directory 2}File 3}String to write to FileNamecreateFileWithInput(){    echo "Entering createFileWithInput"    orgDirectory=${PWD}    cd ${1}    > ${2}    print ${3} >> ${2}    cd ${orgDirectory}    echo "Exiting createFileWithInput"}#Function to create File with Input#Params: 1}directoryNamecreateDir(){    echo "Entering createDir"    mkdir -p ${1}    echo "Exiting createDir"}#Params: 1}FileNamereadLine(){    echo "Entering readLine"    file=${1}    while read line    do        #assign last line to var        var="$line"    done <"$file"    echo "Exiting readLine"}#Check if file exists #Params: 1}FiledoesFileExit(){    echo "Entering doesFileExit"    orgDirectory=${PWD}    cd ${PWD}${dirPath}    #echo ${PWD}    if [[ -e "${1}" ]]; then        echo "${1} exists"    else        echo "${1} does not exist"    fi    cd ${orgDirectory}    echo "Exiting doesFileExit"}#Check if file contains a string quietly#Params: 1}Directory Path 2}File 3}String to seach for in FiledoesFileContainStringQuiet(){    echo "Entering doesFileContainStringQuiet"    orgDirectory=${PWD}    cd ${PWD}${1}    #echo ${PWD}    grep -q ${3} ${2}    if [ ${?} -eq 0 ];then        echo "${3} found in ${2}"    else        echo "${3} not found in ${2}"    fi    cd ${orgDirectory}    echo "Exiting doesFileContainStringQuiet"}#Check if file contains a string with output#Params: 1}Directory Path 2}File 3}String to seach for in FiledoesFileContainString(){    echo "Entering doesFileContainString"    orgDirectory=${PWD}    cd ${PWD}${1}    #echo ${PWD}    grep ${3} ${2}    if [ ${?} -eq 0 ];then        echo "${3} found in ${2}"    else        echo "${3} not found in ${2}"    fi    cd ${orgDirectory}    echo "Exiting doesFileContainString"}#-----------#---Main----#-----------echo "Starting: ${PWD}/${0} with Input Parameters: {1: ${1} {2: ${2} {3: ${3}"#initialize #function call#createDir ${dir} #function call#createFileWithInput ${dir} ${file} ${searchString} #function call#doesFileExit ${file} #function call#if [ ${?} -eq 0 ];then    doesFileContainStringQuiet ${dirPath} ${file} ${searchString} #function call#    doesFileContainString ${dirPath} ${file} ${searchString} #function call#fiecho "Exiting: ${PWD}/${0}"

grepUtil.ksh Output :

grepUtil。ksh输出:

user@foo /tmp$ ksh grepUtil.kshStarting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:Entering createDirExiting createDirEntering createFileWithInputExiting createFileWithInputEntering doesFileExitpoet.txt existsExiting doesFileExitEntering doesFileContainStringQuietpoet found in poet.txtExiting doesFileContainStringQuietEntering doesFileContainStringpoetpoet found in poet.txtExiting doesFileContainStringExiting: /tmp/grepUtil.ksh