Could we help you? Please click the banners. We are young and desperately need the money
find ./ -type f -exec grep -Hn "YourContent" {} \;
find ./ -type f |xargs grep -Hn "abc"
find ./ -type f -exec grep -Hni "YourContent" {} \;
find ./ -type f |xargs grep -Hni "abc"
Extended search script with proper reporting and statistics
The following Bash script is a powerful tool for system administrators who need to search for specific content across multiple files on a Unix-like system. Here's a breakdown of what it does, how it works, and why it's useful:
apt install slocate
This script is particularly useful when:
To search for all PHP files in the themes directory containing the word "contact":
./searchContentInFiles.sh ".*/hosts/.*/themes/.*\.php$" "contact"
Copy the code for this script and put it into a file like "searchContentInFiles.ch". Make the file executable with
chmod +x searchContentInFiles.ch
#! /bin/bash
if [ -z "$1" ] ; then
echo "1. Parameter missing: REGEX string to search for certain files. Put the following to search for all: .*"
echo " More complicated example: \".*/themes/.*/template-[ck]ontact\.php$\""
echo " If you want to search for 'specific-file.php' anywhere: .*specific-file.php"
exit
fi
if [ -z "$2" ] ; then
echo "2. Parameter missing: Regular string to search for within each file. Example: template-name"
exit
fi
# ANSI color codes
RED="\033[1;31m"
GREEN="\033[1;32m"
NOCOLOR="\033[0m"
# Store the regex pattern
HAYSTACK_REGEX="$1"
NEEDLE_REGEX="$2"
# Generate the list of files
echo "Generating file list, please stand by..."
TAIL_FILE_LIST=$(locate --regex "${HAYSTACK_REGEX}")
# Initialize an array to keep track of found files
FOUND_FILES=()
# Loop through each file in the list
for file in $TAIL_FILE_LIST; do
# Check if file exists and is a regular file
if [[ -f "$file" ]]; then
# Search for the regex pattern in the file and capture the output
MATCH_FOUND_ON_LINE=$(grep -En -m1 "${NEEDLE_REGEX}" "$file" | cut -d: -f1)
if [[ -n "${MATCH_FOUND_ON_LINE}" ]]; then
# If pattern found, output the details in green
echo -e "${GREEN}[ ${file} ] ... Found on line [${MATCH_FOUND_ON_LINE}]${NOCOLOR}"
FOUND_FILES+=("[ ${file} ] ... Found on line [${MATCH_FOUND_ON_LINE}]")
else
# If pattern not found, indicate it in red
echo -e "${RED}[ ${file} ] ... Not found${NOCOLOR}"
fi
fi
done
# Display summary of all found files
if [ ${#FOUND_FILES[@]} -eq 0 ]; then
echo -e "\n\n${RED}No files found matching [ ${NEEDLE_REGEX} ]${NOCOLOR}"
else
echo -e "\n\n\nSummary of found files when searching for the pattern `${NEEDLE_REGEX}`:"
for file in "${FOUND_FILES[@]}"; do
echo -e "${GREEN}${file}${NOCOLOR}"
done
fi
This script is a valuable addition to any system administrator's toolkit, offering a quick and efficient way to search through large file systems for specific content.