(Click the public account above to quickly follow)
From: cnblogs
Link: http://www.cnblogs.com/me115/p/3427319.html
This article will introduce the most commonly used tools for text processing in Shell under Linux:
find, grep, xargs, sort, uniq, tr, cut, paste, wc, sed, awk;
The examples and parameters provided are the most commonly used and practical;
My principle for using shell scripts is to write commands in a single line, preferably not exceeding 2 lines;
If there are more complex task requirements, consider using Python;
find File Search
-
Find txt and pdf files
find . \( -name “*.txt” -o -name “*.pdf” \) -print
-
Search for .txt and .pdf using regex
find . -regex “.*\(\.txt|\.pdf\)$”
-iregex: case-insensitive regex
-
Negation parameter
Find all non-txt text files
find . ! -name “*.txt” -print
-
Specify search depth
Print files in the current directory (depth of 1)
find . -maxdepth 1 -type f
Custom Search
-
Search by type:
find . -type d -print // Only list all directories
-type f for files / l for symbolic links
-
Search by time:
-atime access time (in days, for minutes use -amin, similar for others)
-mtime modification time (content has been modified)
-ctime change time (metadata or permission changes)
-
All files accessed in the last 7 days:
find . -atime 7 -type f -print
-
Search by size:
w for bytes, k for kilobytes, M for megabytes, G for gigabytes
Find files larger than 2k
find . -type f -size +2k
Find by permissions:
find . -type f -perm 644 -print // Find all files with executable permissions
Find by user:
find . -type f -user weber -print// Find files owned by user weber
Subsequent Actions After Finding
-
Delete:
Delete all swp files in the current directory:
find . -type f -name “*.swp” -delete
-
Execute actions (powerful exec)
find . -type f -user root -exec chown weber {} \; // Change ownership of all files in the current directory to weber
Note: {} is a special string that will be replaced with the corresponding filename for each matching file;
For example: Copy all found files to another directory:
find . -type f -mtime +10 -name “*.txt” -exec cp {} OLD \;
-
Combine multiple commands
Tips: If you need to execute multiple commands subsequently, you can write them into a script. Then, use -exec to call the script;
-exec ./commands.sh {} \;
-print Delimiter
By default, ‘
‘ is used as the file delimiter;
-print0 uses ‘