Jak sprawdzić, czy string istnieje w pliku z Bash?

Mam plik zawierający nazwy katalogów:

my_list.txt :

/tmp
/var/tmp

Chciałbym sprawdzić w Bash zanim dodam nazwę katalogu, jeśli ta nazwa już istnieje w pliku.

Author: codeforester, 2011-01-20

11 answers

grep -Fxq "$FILENAME" my_list.txt

Status wyjścia wynosi 0 (true), Jeśli nazwa została znaleziona, 1 (false), jeśli nie, więc:

if grep -Fxq "$FILENAME" my_list.txt
then
    # code if found
else
    # code if not found
fi

Oto odpowiednie sekcje strony man dla grep:

grep [options] PATTERN [FILE...]

-F, --fixed-strings
       Interpret PATTERN as a list of fixed strings, separated by  new-
       lines, any of which is to be matched.

-x, --line-regexp
       Select only those matches that exactly match the whole line.

-q, --quiet, --silent
       Quiet; do not write anything to standard output.  Exit  immedi-
       ately  with  zero status if any match is found, even if an error
       was detected.  Also see the -s or --no-messages option.
 503
Author: Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-16 09:57:16

W odniesieniu do następującego rozwiązania:

grep -Fxq "$FILENAME" my_list.txt

W przypadku, gdy zastanawiasz się (tak jak ja) co -Fxq oznacza po angielsku:

  • F: wpływa na interpretację wzorca (stały ciąg znaków zamiast regex)
  • x: Dopasuj całą linię
  • q: Shhhhh... minimal printing

Z pliku man:

-F, --fixed-strings
    Interpret  PATTERN  as  a  list of fixed strings, separated by newlines, any of which is to be matched.
    (-F is specified by POSIX.)
-x, --line-regexp
    Select only those matches that exactly match the whole line.  (-x is specified by POSIX.)
-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.)
 77
Author: Kuf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-30 19:25:35

Trzy metody w moim umyśle:

1) krótki test na nazwę w ścieżce (nie jestem pewien, czy to może być twój przypadek)

ls -a "path" | grep "name"


2) krótki test dla ciągu znaków w pliku

grep -R "string" "filepath"


3) dłuższy skrypt bash przy użyciu regex:

#!/bin/bash

declare file="content.txt"
declare regex="\s+string\s+"

declare file_content=$( cat "${file}" )
if [[ " $file_content " =~ $regex ]] # please note the space before and after the file content
    then
        echo "found"
    else
        echo "not found"
fi

exit

Powinno to być szybsze, Jeśli masz do testowania wielu łańcuchów na zawartości pliku za pomocą pętli, na przykład zmieniając regex w dowolnym cyklu.

 29
Author: Luca Borrione,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-29 21:05:51

Prostszy sposób:

if grep "$filename" my_list.txt > /dev/null
then
   ... found
else
   ... not found
fi

Wskazówka: Wyślij do /dev/null jeśli chcesz mieć status zakończenia polecenia, ale nie wyjścia.

 14
Author: imwilsonxu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-12 08:24:03

Jeśli dobrze zrozumiałem twoje pytanie, powinno to zrobić to, czego potrzebujesz.

  1. możesz określić katalog, który chcesz dodać poprzez zmienną $ check
  2. jeśli katalog jest już na liście, wyjściem jest "dir already listed"
  3. jeśli katalog nie znajduje się jeszcze na liście, jest dołączany do my_list.txt

W jednej linii: check="/tmp/newdirectory"; [[ -n $(grep "^$check\$" my_list.txt) ]] && echo "dir already listed" || echo "$check" >> my_list.txt

 4
Author: lecodesportif,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-25 13:37:41

Najprostszym i najprostszym sposobem byłoby:

isInFile=$(cat file.txt | grep -c "string")


if [ $isInFile -eq 0 ]; then
   #string not contained in file
else
   #string is in file at least once
fi

Grep-C zwróci liczbę, ile razy łańcuch znaków występuje w pliku.

 4
Author: Christian737,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-06 10:47:47

Jeśli chcesz tylko sprawdzić istnienie jednej linii, nie musisz tworzyć pliku. Np.,

if grep -xq "LINE_TO_BE_MATCHED" FILE_TO_LOOK_IN ; then
  # code for if it exists
else
  # code for if it does not exist
fi  
 2
Author: gordon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-29 20:41:06

Moja wersja za pomocą fgrep

  FOUND=`fgrep -c "FOUND" $VALIDATION_FILE`
  if [ $FOUND -eq 0 ]; then
    echo "Not able to find"
  else
    echo "able to find"     
  fi  
 1
Author: Rudy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-11 07:27:45
grep -E "(string)" /path/to/file || echo "no match found"

- Opcja e sprawia, że grep używa wyrażeń regularnych

 1
Author: David Okwii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-31 09:52:14

Rozwiązanie bez grepa, działa dla mnie:

MY_LIST=$( cat /path/to/my_list.txt )



if [[ "${MY_LIST}" == *"${NEW_DIRECTORY_NAME}"* ]]; then
  echo "It's there!"
else
echo "its not there"
fi

Na podstawie: https://stackoverflow.com/a/229606/3306354

 0
Author: AndrewD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-31 09:22:51
if grep -q "$Filename$" my_list.txt
   then
     echo "exist"
else 
     echo "not exist"
fi
 -1
Author: Triangle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-02 13:44:45