Kategori arşivi: Shell Script

linux kelime dosyada yer alıyor mu

Linux’ta bir kelimenin (string) bir dosyada yer alıp almadığını bulan shell script.
Aşağıdaki kod bir sh dosyasına (searched_string_in_file.sh) kaydedilip kullanılabilir.

# return
# 0: searched string found in file
# 1: searched string not found in file
# 2: file not found
# 3: wrong parameters send
# 9: help

echo_usage() {
  echo "usage: search_string.sh /full/file/path.ext serched_string"
  echo "or"
  echo "usage: search_string.sh /full/file/path.ext \"serched string\""
  echo ""
}

if [ -n "$1" ]; then
  if [ "$1" == "help" ]; then
    echo_usage
    exit 9
  else
    if [ -n "$2" ]; then
      # does file exist in current working directory or in full path
      # does file exist
      # does string place in file
      if [ -f "$1" ]; then
        echo "OK"
        is_ok=`grep "$2" "$1"`
        if [ $is_ok == "" ]; then
          echo "found"
          exit 0
        else
          echo "searched string not found"
          exit 1
        fi
      else
        echo "file not found"
        exit 2
      fi
    else
      echo_usage
      exit 3
    fi
  fi
else
  echo_usage
  exit 3
fi