MST

星途 面试题库

面试题:Bash实现复杂文件内容替换

给定一个文件info.txt,文件内有多行内容,每行格式为'id:name:age',例如'1:Alice:25',现在要求将所有年龄大于30的人的年龄增加5,并更新到文件中,使用Bash脚本实现。
48.0万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

# 临时文件
temp_file=$(mktemp)

while IFS=: read -r id name age; do
    if (( age > 30 )); then
        (( age += 5 ))
    fi
    echo "$id:$name:$age" >> "$temp_file"
done < info.txt

# 用临时文件覆盖原文件
mv "$temp_file" info.txt