Linux: Locating text file from a string input

filessearch

I have started to use Linux and I'm practicing using/making codes to locate and do things. I need code that locates any file from a string of input.

Best Answer

Two options

  • find. e.g. find ~/Documents -name '*finances*'

  • locate (requires up to date index with updatedb). e.g. locate finances

to put this in a script, you can do

#!/bin/bash

# pattern="${1}" # first argument to script
# alternatively, ask user
echo "Enter a pattern to be searched for in the current directory"
read pattern    

# search current directory `.`
matches=$(find . -type f -name "${pattern}")

# $matches is now a list of matching files
echo "$matches"

careful about shell gobbing, i.e. a * in the pattern is firstly expanded by bash to match filenames in the current directory.

The multitude of options to find is documented: man find.

Welcome to Linux!

Related Question