web-dev-qa-db-fra.com

Vérifiez si le fichier existe et s'il contient une chaîne spécifique

Je veux vérifier si file2.sh existe et aussi si un mot spécifique, poet fait partie du fichier. J'utilise grep pour créer la variable used_var.

#!/bin/ksh

file_name=/home/file2.sh                  
used_var=`grep "poet" $file_name`    

Comment puis-je vérifier si used_var a une certaine valeur?

32
randeepsp

Au lieu de stocker la sortie de grep dans une variable puis de vérifier si la variable est vide, vous pouvez le faire:

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

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

Voici quelques tests couramment utilisés:

   -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

Exemple:

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

if grep -q "poet" $file_name; then
  ..
fi
14
ghostdog74

test -e testera si un fichier existe ou non. La commande test renvoie une valeur nulle si le test réussit ou 1 sinon.

Le test peut être écrit soit comme test -e ou en utilisant []

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

Sauf si vous avez réellement besoin de la sortie de grep, vous pouvez tester la valeur de retour car grep renverra 1 s'il n'y a pas de correspondance et zéro s'il y en a.

En termes généraux, vous pouvez tester si une chaîne n'est pas vide en utilisant [ "string" ] qui renverra 0 si non vide et 1 si vide

6
Steve Weet

Si le binaire test est installé ou que ksh a une fonction intégrée correspondante, vous pouvez l'utiliser pour effectuer vos vérifications. Habituellement /bin/[ est un lien symbolique vers test:

if [ -e "$file_name" ]; then
  echo "File exists"
fi

if [ -z "$used_var" ]; then
  echo "Variable is empty"
fi
4
joschi

Vous devez utiliser le grep-q drapeau pour une sortie silencieuse. Consultez les pages de manuel ci-dessous:

sortie man 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.)

Ce script KornShell (ksh) présente la sortie silencieuse grep et est une solution à votre question.

grepUtil.ksh:

#!/bin/ksh

#Initialize Variables
file=poet.txt
var=""
dir=tempDir
dirPath="/"${dir}"/"
searchString="poet"

#Function to initialize variables
initialize(){
    echo "Entering initialize"
    echo "Exiting initialize"
}

#Function to create File with Input
#Params: 1}Directory 2}File 3}String to write to FileName
createFileWithInput(){
    echo "Entering createFileWithInput"
    orgDirectory=${PWD}
    cd ${1}
    > ${2}
    print ${3} >> ${2}
    cd ${orgDirectory}
    echo "Exiting createFileWithInput"
}

#Function to create File with Input
#Params: 1}directoryName
createDir(){
    echo "Entering createDir"
    mkdir -p ${1}
    echo "Exiting createDir"
}

#Params: 1}FileName
readLine(){
    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}File
doesFileExit(){
    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 File
doesFileContainStringQuiet(){
    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 File
doesFileContainString(){
    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#
fi
echo "Exiting: ${PWD}/${0}"

Sortie grepUtil.ksh:

user@foo /tmp
$ ksh grepUtil.ksh
Starting: /tmp/grepUtil.ksh with Input Parameters: {1:  {2:  {3:
Entering createDir
Exiting createDir
Entering createFileWithInput
Exiting createFileWithInput
Entering doesFileExit
poet.txt exists
Exiting doesFileExit
Entering doesFileContainStringQuiet
poet found in poet.txt
Exiting doesFileContainStringQuiet
Entering doesFileContainString
poet
poet found in poet.txt
Exiting doesFileContainString
Exiting: /tmp/grepUtil.ksh
1
javaPlease42