Skip to content

Instantly share code, notes, and snippets.

@santisbon
Last active August 4, 2024 06:45
Show Gist options
  • Save santisbon/5283059 to your computer and use it in GitHub Desktop.
Save santisbon/5283059 to your computer and use it in GitHub Desktop.
How to find files and text in the shell and work with them. #linux #search

Assuming there's a /test folder with .txt files in it. Note how the * character is escaped to prevent expansion.

Linux and Cygwin

find /test -name \*.txt -exec sed -i 's/oldValue/newValue/g' {} \;

OS X. In sed the -i option edits files in-place instead of printing to standard output and requires a file extension.
Use "" to overwrite the file in place.

find /test -name \*.txt -exec sed -i "" 's/oldValue/newValue/g' {} \;

Find a string in current directory and subdirectories, print line number, exclude some directories.

grep -rn --exclude-dir={node_modules,amplify} mystring .

In zsh you can use glob expansion to do something like this: You want to list the python executables and check their version.
For each file in /usr/ (recursively) named "python" followed by anything, followed by a digit, expanding only executable simple files (not directories or links) do the following:
print the file name (no line breaks), a tab, and then execute the file with the --version option.

for file in /usr/**/python*[[:digit:]](*); do echo -n $file '\t'; $file --version; done
/usr/bin/python3 	Python 3.8.9
/usr/local/Cellar/[email protected]/3.9.13_1/Frameworks/Python.framework/Versions/3.9/bin/python3.9 	Python 3.9.13
/usr/local/anaconda3/bin/python3.9 	Python 3.9.12
/usr/local/anaconda3/envs/snakes/bin/python3.10 	Python 3.10.4
/usr/local/anaconda3/envs/snowflakes/bin/python3.10 	Python 3.10.4
/usr/local/anaconda3/pkgs/python-3.10.4-hdfd78df_0/bin/python3.10 	Python 3.10.4
/usr/local/anaconda3/pkgs/python-3.9.12-hdfd78df_0/bin/python3.9 	Python 3.9.12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment