本文共 3179 字,大约阅读时间需要 10 分钟。
基础命令工具
find、grep、sort、uniq、sed、awk、cut、tr、wc、xargs、pasteShell脚本的编写原则
命令应尽量单行书写,便于阅读和维护查找特定文件类型
find . \( -name "*.txt" -o -name "*.pdf" \) -print
使用正则表达式查找文件
find . -regex ".*\(\.txt|\.pdf\)$"
排除特定文件类型
find . ! -name "*.txt" -print
指定搜索深度
find . -maxdepth 1 -type f
按文件类型搜索
find . -type d -print
按时间搜索
find . -atime 7 -type f -print
按大小搜索
find . -type f -size +2k
按权限搜索
find . -type f -perm 644 -print
按用户搜索
find . -type f -user weber -print
删除匹配文件
find . -type f -name "*.swp" -delete
执行命令
find . -type f -user root -exec chown weber {} \;
复制文件
find . -type f -mtime +10 -name "*.txt" -exec cp {} OLD \;
组合命令
find . -type f -mtime +10 -name "*.txt" -exec ./commands.sh {} \;
-print的定界符
基础用法
grep "match_patten" file
常用参数
在多级目录中递归搜索
grep "class" . -R -n
匹配多个模式
grep -e "class" -e "virtual" file
使用正则表达式
grep -r ".*\(\.txt|\.pdf\)" .
输出文件名
grep -lZ "test" file* | xargs -0 rm
sort -nrk 1 data.txt
sort -bd data
sort unsort.txt | uniq
sort unsort.txt | uniq -c
sort unsort.txt | uniq -d
sort unsort.txt | uniq -s 1
替换文本
sed 's/text/replace_text/' file
全局替换
sed 's/text/replace_text/g' file
替换空白行
sed '/^$/d' file
变量转换
echo this is an example | sed 's/\w+/&/g' > this%20is%20an%20example
子串匹配
sed 's/hello\([0-9]\)/\1/'
基本结构
awk ' BEGIN { statements } statements END { statements }'
打印当前行
echo -e "line1\nline2" | awk '{print}'
打印特定字段
awk '{print $2, $3}' file
统计文件行数
awk 'END { print NR }' file
累加数字
echo -e "1\n 2\n 3\n 4\n" | awk '{sum += $1; print sum}'
使用正则表达式过滤行
awk '/linux/' file
读取命令输出
echo "grep root /etc/passwd" | awk '{getline cmdout; print cmdout}'
实现循环
for(i in array){print array[i];}
截取特定字段
cut -f2,4 filename
去除特定字段
cut -f3 --complement filename
指定定界符
cat -f2 -d";" filename
按字段范围切分
cut -c1-5 file
按字符切分
cut -c-2 file
字符转换
echo 12345 | tr '0-9' '9876543210'
删除字符
cat file | tr -d '0-9'
求补集
cat file | tr -c '0-9'
压缩空格
cat file | tr -s ' '
字符类匹配
tr '[:lower:]' '[:upper:]'
wc -l file
wc -w file
wc -c file
paste file1 file2
paste file1 file2 -d ","
cat file.txt | xargs
cat single.txt | xargs -n 3
find source_dir/ -type f -name "*.cpp" -print0 | xargs -0 wc -l
while read line; do echo $line; done < file.txt
cat file.txt | (while read line; do echo $line; done)
for word in $line; do echo $word; done
for((i=0; i<${#word}; i++)); do echo ${word:i:1}; done
以上命令和技巧为Shell脚本编写提供了丰富的工具,能够高效处理文本和文件操作。
转载地址:http://xwufk.baihongyu.com/