本文目录导读:

Shell 脚本转换
#!/bin/bash
# file: case_convert.sh
# 字符串转大写
str="hello world"
echo ${str^^} # HELLO WORLD
# 字符串转小写
echo ${str,,} # hello world
# 首字母大写
echo ${str^} # Hello world
转换转为大写
cat input.txt | tr '[:lower:]' '[:upper:]' > output.txt
# 或使用 awk
awk '{print toupper($0)}' input.txt > output.txt
Python 脚本
#!/usr/bin/env python3
# file: case_convert.py
def convert_case(text, mode='upper'):
"""转换大小写"""
if mode == 'upper':
return text.upper()
elif mode == 'lower':
return text.lower()
elif mode == 'title':
return text.title()
elif mode == 'capitalize':
return text.capitalize()
elif mode == 'swap':
return text.swapcase()
else:
return text
# 批量处理文件
def convert_file(input_file, output_file, mode='upper'):
with open(input_file, 'r') as f_in:
with open(output_file, 'w') as f_out:
for line in f_in:
f_out.write(convert_case(line, mode))
# 交互式使用
if __name__ == '__main__':
text = input("请输入文本: ")
print("1. 全部大写")
print("2. 全部小写")
print("3. 首字母大写")
print("4. 每个单词首字母大写")
choice = input("选择转换方式 (1-4): ")
modes = {'1': 'upper', '2': 'lower', '3': 'capitalize', '4': 'title'}
result = convert_case(text, modes.get(choice, 'upper'))
print(f"转换结果: {result}")
JavaScript 脚本
// file: case_convert.js
// Node.js 版本
const fs = require('fs');
const readline = require('readline');
function convertCase(text, mode = 'upper') {
const converters = {
'upper': str => str.toUpperCase(),
'lower': str => str.toLowerCase(),
'title': str => str.replace(/\b\w/g, c => c.toUpperCase()),
'camel': str => str.replace(/[-_]\w/g, c => c[1].toUpperCase()),
'snake': str => str.replace(/[A-Z]/g, c => '_' + c.toLowerCase()),
'kebab': str => str.replace(/[A-Z]/g, c => '-' + c.toLowerCase())
};
return converters[mode] ? converters[mode](text) : text;
}
// 文件处理
function convertFile(inputFile, outputFile, mode) {
const content = fs.readFileSync(inputFile, 'utf8');
const converted = convertCase(content, mode);
fs.writeFileSync(outputFile, converted);
console.log(`文件已转换并保存到 ${outputFile}`);
}
// 命令行交互
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('请输入文本: ', (text) => {
console.log('\n选项:');
console.log('1. 大写 (UPPER)');
console.log('2. 小写 (lower)');
console.log('3. 标题 (Title Case)');
console.log('4. 驼峰 (camelCase)');
console.log('5. 蛇形 (snake_case)');
console.log('6. 连字符 (kebab-case)');
rl.question('选择 (1-6): ', (choice) => {
const modes = ['upper', 'lower', 'title', 'camel', 'snake', 'kebab'];
const result = convertCase(text, modes[parseInt(choice) - 1]);
console.log(`\n结果: ${result}`);
rl.close();
});
});
批处理脚本 (Windows)
@echo off
REM file: case_convert.bat
REM 字符串操作用于批处理需要第三方工具或复杂逻辑
REM 使用 PowerShell 命令
set "str=Hello World"
REM 转换为大写
powershell -Command "Write-Host ('%str%'.ToUpper())"
REM 转换为小写
powershell -Command "Write-Host ('%str%'.ToLower())"
REM 批量处理文件
powershell -Command "$content = Get-Content input.txt; $content.ToUpper() | Set-Content output.txt"
自动检测并转换脚本
#!/usr/bin/env python3
# file: auto_case_detector.py
import re
def detect_and_convert(text):
"""自动检测大小写规则并转换"""
# 检测当前格式
if text.isupper():
print("检测: 全大写 → 转换为小写")
return text.lower()
elif text.islower():
print("检测: 全小写 → 转换为首字母大写")
return text.capitalize()
elif text.istitle():
print("检测: 标题格式 → 转换为大写")
return text.upper()
elif re.match(r'^[a-z]+[A-Z]', text):
print("检测: 驼峰格式 → 转换为蛇形")
return re.sub(r'([A-Z])', r'_\1', text).lower()
else:
print("无法确定格式,保留原样")
return text
# 测试
test_strings = [
"HELLO WORLD",
"hello world",
"Hello World",
"helloWorld",
"hello_world"
]
for s in test_strings:
result = detect_and_convert(s)
print(f"原: '{s}' → 新: '{result}'\n")
使用示例
命令行使用
# Python 单行转换
python3 -c "print('hello world'.upper())"
# Shell 单行转换
echo "Hello World" | tr 'A-Z' 'a-z'
# 交互式使用
chmod +x case_convert.sh
./case_convert.sh
批量处理多个文件
# 批量转换当前目录所有 .txt 文件为大写
for file in *.txt; do
python3 -c "open('$file', 'w').write(open('$file').read().upper())"
done
建议
- 简单转换:使用 Shell 的
tr或${var^^}语法 - 复杂规则:使用 Python 或 JavaScript
- 批量处理:Python 脚本更灵活
- 跨平台:Python 是最好的选择
需要特定场景的转换(如只转换文件名、只转换某些字符等)吗?我可以提供更具体的方法。