find


Bash Function to print out the files and the lines that contain a needle

The following code will create a function in bash that accepts two parameters (1: the place to search in, 2: the value to search for).

You can place it in your ~/.bashrc file to have it available whenever you open a bash shell.

#1. Copy/paste the below lines in your .bashrc

#takes 2 parameters (1: the haystack to search in, 2: the needle)
# Will print out the files and the lines that contain the needle
xfind(){
  FIND_VAR="$2";
  STACK="$1";
  if [ -f "$STACK" ] || [ -d "$STACK" ]; then
    find "$STACK" \
      -exec grep --color "$FIND_VAR" -sl '{}' \; \
      -exec grep "$FIND_VAR" -s '{}' \;
  else
    echo "ERROR: No file or folder with the name '$STACK' exist";
  fi
}
#2. Run source ~/.bashrc -- to reload 

Usage examples:

xfind . "bar";
xfind /etc/ "conf";

Recursively change extension of multiple files using find

Assuming you have a whole bunch of files that you need to change their extension from one to another, you can use the following commands after setting the values for the BEFORE and the AFTER variables to the values you need.

BEFORE='.txt'; AFTER='.csv'; find . -type f -name "*$BEFORE" -exec bash -c 'mv "$1" "${1%$2}$3"' _ '{}' "$BEFORE" "$AFTER" \;

What the above will do is: after setting the two input variables it will call find in the current directory (with recursion) and find all files that their suffix is the value you set in BEFORE. Then, for each match it will create a new shell terminal in which it will rename the file by removing the old suffix and then attaching the new one. We pass the input variables as parameters to the new shell and that is why inside the code of the shell we are using variables $1, $2 and $3. The reason we had to issue a new shell is because we wanted to reuse the ‘{}’ variable.


Linux Bash: How to find a string inside C/C++ Source and Header Files

Just issue the following in the folder of the source codes and replace ‘FIND ME’ with the string you want to query:

find -O3 . -regex '.*\.\(c\|cpp\|h\)

You can change the contents of the regular expression to search in different file extensions (file types).  -exec grep 'FIND ME!' -sl '{}' \;

You can change the contents of the regular expression to search in different file extensions (file types).