本文目录导读:

在Shell脚本中,按行随机打乱文件内容最常用的方法是使用 shuf 命令,以下是几种实现方式:
使用 shuf 命令(最推荐)
# 基本用法 shuf input.txt > output.txt # 或者直接覆盖原文件 shuf -o input.txt input.txt # 限制输出行数(比如只输出前10行) shuf -n 10 input.txt # 搭配 head/tail 使用 shuf input.txt | head -n 20
使用 sort -R 命令
# 使用随机排序 sort -R input.txt > output.txt # 或者使用更随机的选项 sort --random-source=/dev/urandom -R input.txt
使用 awk 脚本(不依赖外部命令)
awk 'BEGIN {srand()} {print rand() "\t" $0}' input.txt | sort -n | cut -f2- > output.txt
完整的Shell脚本示例
#!/bin/bash
# 检查输入文件是否存在
if [ ! -f "$1" ]; then
echo "Usage: $0 <filename>"
exit 1
fi
input_file="$1"
output_file="${input_file%.*}_shuffled.${input_file##*.}"
# 方法1:使用shuf
if command -v shuf &> /dev/null; then
echo "Using shuf command..."
shuf "$input_file" > "$output_file"
echo "Shuffled file saved as: $output_file"
# 方法2:如果shuf不可用,使用awk方法
elif command -v awk &> /dev/null; then
echo "shuf not found, using awk method..."
awk 'BEGIN {srand()} {print rand() "\t" $0}' "$input_file" | sort -n | cut -f2- > "$output_file"
echo "Shuffled file saved as: $output_file"
else
echo "Error: No suitable command found"
exit 1
fi
高级用法
# 结合grep,只打乱匹配特定模式的行 grep "^http" urls.txt | shuf > shuffled_urls.txt # 保留文件头部(比如CSV文件) head -1 data.csv > shuffled_data.csv && tail -n +2 data.csv | shuf >> shuffled_data.csv # 多次shuffle并去重 shuf input.txt | awk '!seen[$0]++' > unique_shuffled.txt
注意事项
- shuf 是GNU coreutils的一部分,在大多数Linux发行版中默认安装
- 在macOS上,
shuf可能不可用,但可以通过brew install coreutils安装,或使用gshuf - sort -R 在某些系统上可能不产生真正的随机排序
- 对于大文件,
shuf性能最好
推荐优先使用 shuf 命令,因为它就是专门为这个目的设计的,效率高且随机性好。