[string] How to test if string exists in file with Bash?

I have a file that contains directory names:

my_list.txt :

/tmp
/var/tmp

I'd like to check in Bash before I'll add a directory name if that name already exists in the file.

This question is related to string bash file

The answer is


Slightly similar to other answers but does not fork cat and entries can contain spaces

contains() {
    [[ " ${list[@]} " =~ " ${1} " ]] && echo 'contains' || echo 'does not contain'
}

IFS=$'\r\n' list=($(<my_list.txt))

so, for a my_list.txt like

/tmp
/var/tmp
/Users/usr/dir with spaces

these tests

contains '/tmp'
contains '/bin'
contains '/var/tmp'
contains '/Users/usr/dir with spaces'
contains 'dir with spaces'

return

exists
does not exist
exists
exists
does not exist

A grep-less solution, works for me:

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

based on: https://stackoverflow.com/a/229606/3306354


Simpler way:

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

Tip: send to /dev/null if you want command's exit status, but not outputs.


The @Thomas's solution didn't work for me for some reason but I had longer string with special characters and whitespaces so I just changed the parameters like this:

if grep -Fxq 'string you want to find' "/path/to/file"; then
    echo "Found"
else
    echo "Not found"
fi

Hope it helps someone


if grep -q "$Filename$" my_list.txt
   then
     echo "exist"
else 
     echo "not exist"
fi

grep -E "(string)" /path/to/file || echo "no match found"

-E option makes grep use regular expressions


I was looking for a way to do this in the terminal and filter lines in the normal "grep behaviour". Have your strings in a file strings.txt:

string1
string2
...

Then you can build a regular expression like (string1|string2|...) and use it for filtering:

cmd1 | grep -P "($(cat strings.txt | tr '\n' '|' | head -c -1))" | cmd2

Edit: Above only works if you don't use any regex characters, if escaping is required, it could be done like:

cat strings.txt | python3 -c "import re, sys; [sys.stdout.write(re.escape(line[:-1]) + '\n') for line in sys.stdin]" | ...

My version using fgrep

  FOUND=`fgrep -c "FOUND" $VALIDATION_FILE`
  if [ $FOUND -eq 0 ]; then
    echo "Not able to find"
  else
    echo "able to find"     
  fi  

Here's a fast way to search and evaluate a string or partial string:

if grep -R "my-search-string" /my/file.ext
then
    # string exists
else
    # string not found
fi

You can also test first, if the command returns any results by running only:

grep -R "my-search-string" /my/file.ext

Regarding the following solution:

grep -Fxq "$FILENAME" my_list.txt

In case you are wondering (as I did) what -Fxq means in plain English:

  • F: Affects how PATTERN is interpreted (fixed string instead of a regex)
  • x: Match whole line
  • q: Shhhhh... minimal printing

From the man file:

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

Easiest and simplest way would be:

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 will return the count of how many times the string occurs in the file.


If I understood your question correctly, this should do what you need.

  1. you can specifiy the directory you would like to add through $check variable
  2. if the directory is already in the list, the output is "dir already listed"
  3. if the directory is not yet in the list, it is appended to my_list.txt

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


If you just want to check the existence of one line, you do not need to create a file. E.g.,

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  

grep -Fxq "String to be found" | ls -a
  • grep will helps you to check content
  • ls will list all the Files

Three methods in my mind:

1) Short test for a name in a path (I'm not sure this might be your case)

ls -a "path" | grep "name"


2) Short test for a string in a file

grep -R "string" "filepath"


3) Longer bash script using 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

This should be quicker if you have to test multiple string on a file content using a loop for example changing the regex at any cicle.


Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?