fd, grep and sed
These 3 commands are all CLI tools that can enable searching for files, searching for text, find and replace in files
fd
`fd` is a fast, user-friendly alternative to
the find command. It has some extra features compared to find such as ignore
files in .gitignore, syntax highlighting, faster and more.
fd Options
• -t [f|d] - Specify the type; file or folder
• -e [extension] - Specify the file extension (e.g 'md')
• -x [command] - A command to execute for each found record
Using fd
# Find all folders in current directory
fd --type d# Find all markdown files in current directory
fd -e md# Output all log files in current directory
fd -e log -x catgrep
Use grep to check if a file contains a pattern. You can also output each line that matches with the lines above or below.
grep Options
• -v - Invert match (match lines NOT containing pattern)
• -i - Ignore case
• -c - Count the number of matches
• -r - Recursively search in subdirectories
• -n - Output line number
• -A [number] - Output number of lines after match
• -B [number] - Output number of lines before match
Using grep
# Find the number of occurrences of 'mine' in a file
grep -c 'mine' file.txt# Find all files containing 'my_variable_name'
grep -r 'my_variable_name' .# Save into a file all occurrences of 'bob' with 5 lines above and below the match
grep -r -A 5 -B 5 'bob' . > output.txtsed
Use sed to find and replace text in files.
sed Options
• -i - Edit files in-place
• -e [command] - A command to execute for each found record
Using sed
# Replace all occurrences of 'old' with 'new' in a file
sed -i 's/old/new/g' file.txt# Display the changes:
# Replace (case insensitive) 'OLD' with 'new'
sed -i 's/OLD/new/gi' file.txtAll Together Now
If we put these all together we could create a find and replace for all matches of a pattern in a directory:
# '{}' is the file path passed from fd
fd -e md -x sed -i 's/old/new/g' {}Display the count of matches for a variable in the current directory:
fd -e md -x grep -c 'my_variable_name' {}Output the number of files that contains the word 'bob':
fd -t f -x grep -c 'bob' {} | grep -v '^0$' | wc -lRegex Capture Groups What are Pointers?