Bash and Linux 5 cheatsheet

Bash and Linux 5: Searching and text

8 common Bash and Linux 5 tasks.

Search file contents

Search a folder recursively and show file names and line numbers.

grep -rn "TODO" .

Find files by name

Find files whose name matches a pattern.

find . -name "*.log"

Find files changed recently

Find files modified in the last day.

find . -type f -mtime -1

Count lines

Count the lines in a file.

wc -l file.txt

Count duplicate lines

Sort lines and count how often each appears, most common first.

sort file.txt | uniq -c | sort -nr

Replace text in a file

Replace every occurrence of a word in place.

sed -i 's/old/new/g' file.txt

Caution: -i edits the file in place. On macOS use sed -i '' instead. Test without -i first.

Print one column

Print the second whitespace-separated column of each line.

awk '{print $2}' file.txt

Run a command on a list of files

Pass matching file names to another command.

find . -name "*.tmp" -print0 | xargs -0 rm

Caution: Runs rm on every match. Replace rm with ls first to check the list.

Was this page helpful?