# 函数1:替换文件的特定行
replace_lines() {
local file_name="$1"
# 定义文件名
local input_file="${file_name}.cell"
local output_file="CHGCAR_${file_name}.vasp"
local temp_file="${output_file}.tmp"
# 提取第2-4行的内容
local replacement
replacement=$(sed -n '2,4p' "$input_file")
# 使用awk替换目标文件的第3-5行
awk -v repl="$replacement" '
BEGIN {
split(repl, lines, "\n") # 将替换内容按换行符分割
}
NR >= 3 && NR <= 5 { # 替换目标文件的第3-5行
print lines[NR-2]
next
}
{ print } # 保留其他行
' "$output_file" > "$temp_file"
# 替换原文件
mv "$temp_file" "$output_file"
echo "完成替换:$input_file 的第2-4行已替换到 $output_file 的第3-5行"
}
# 函数2:统计元素及个数
count_words_in_array() {
# 初始化标志
in_block=false
# 声明关联数组用于统计单词出现次数
declare -A word_count
# 用于记录单词的出现顺序
order=()
# 读取文件并统计单词
while IFS= read -r line; do
# 检查是否遇到%BLOCK POSITIONS_FRAC
if [[ "$line" == "%BLOCK POSITIONS_FRAC" ]]; then
in_block=true
continue
fi
# 检查是否遇到%ENDBLOCK POSITIONS_FRAC
if [[ "$line" == "%ENDBLOCK POSITIONS_FRAC" ]]; then
in_block=false
continue
fi
# 如果在%BLOCK POSITIONS_FRAC和%ENDBLOCK POSITIONS_FRAC之间,提取第一个单词并统计
if $in_block; then
first_word=$(echo "$line" | awk '{print $1}')
# 如果该单词第一次出现,记录它的顺序
if [[ -z "${word_count["$first_word"]}" ]]; then
order+=("$first_word")
fi
# 更新该单词的计数
((word_count["$first_word"]++))
fi
done < "$1"
# 输出按顺序排列的单词
for word in "${order[@]}"; do
echo -n "$word "
done
echo
# 输出每个单词的计数,按照单词的顺序
for word in "${order[@]}"; do
echo -n "${word_count[$word]} "
done
echo
}
# 函数3:添加元素及个数
insert_count_to_file() {
local file_name="$1"
# 获取统计结果
output=$(count_words_in_array "$file_name.cell")