实用工具与技巧
1 tr命令 - 字符转换
tr(translate)命令用于字符转换或删除。
基本语法:
bash
tr [选项] SET1 [SET2]
大小写转换示例:
bash
head -n 5 /etc/passwd | tr 'a-z' 'A-Z' > ./path/passwd.out
命令解析:
head -n 5 /etc/passwd取passwd文件的前5行|管道符,将前一命令的输出作为后一命令的输入tr 'a-z' 'A-Z'将所有小写字母转换为大写字母> ./path/passwd.out将结果保存到文件
验证结果:
bash
cat ./path/passwd.out # 查看转换后的内容,全部变为大写
其他tr用法:
bash
# 大写转小写
echo "HELLO WORLD" | tr 'A-Z' 'a-z'
# 输出: hello world
# 删除数字
echo "abc123def456" | tr -d '0-9'
# 输出: abcdef
# 删除空格
echo "hello world" | tr -d ' '
# 输出: helloworld
# 压缩重复字符
echo "hello world" | tr -s ' '
# 输出: hello world
# 替换字符
echo "hello" | tr 'el' 'ip'
# 输出: hippo
2 重定向的实战组合
示例1: 分离输出用于调试
bash
# 测试不存在的命令
ls xxx
# 方式1: 只保存正确输出
ls xxx 1>./path/out.txt
# 错误信息显示在终端,out.txt为空
# 方式2: 只保存错误输出
ls xxx 2>./path/no.out
# 错误信息保存到no.out,终端无显示
# 方式3: 同时保存正确和错误输出
ls xxx 1>./path/out.txt 2>&1
# 所有输出都保存到out.txt
示例2: 屏蔽错误信息
bash
# 将错误输出丢弃到/dev/null(黑洞设备)
command 2>/dev/null
# 实际应用
find / -name "*.txt" 2>/dev/null # 忽略权限错误
示例3: 同时保存到文件和显示在屏幕
bash
# 使用tee命令
ls -la | tee output.txt
# 内容既显示在屏幕上,又保存到output.txt
# 追加模式
ls -la | tee -a output.txt
重定向实战案例
1 日志记录
创建带时间戳的日志:
bash
echo "$(date): 系统启动" >> /var/log/myapp.log
分离正常日志和错误日志:
bash
./myprogram 1>>app.log 2>>error.log
2 批量处理
批量文件转换:
bash
# 将所有txt文件转为大写
for file in *.txt; do
tr 'a-z' 'A-Z' < "$file" > "${file}.upper"
done
3 数据清洗
提取特定格式数据:
bash
# 提取IP地址并去重
grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' access.log | sort -u > ips.txt
4 配置文件生成
使用Here Document创建配置:
bash
cat > nginx.conf << 'EOF'
server {
listen 80;
server_name example.com;
root /var/www/html;
}
EOF
注意使用'EOF'(带引号)可以防止变量展开。