面试题答案
一键面试实现思路
- 使用
while read
逐行读取大文本文件。 - 对每行数据按照
,
进行分割,获取年龄和城市信息。 - 判断年龄是否大于30岁且城市是否为“北京”。
- 如果满足条件,将该行数据输出到新文件中。
脚本代码
#!/bin/bash
input_file="large_text_file.txt"
output_file="filtered_records.txt"
while read line; do
name=$(echo $line | cut -d ',' -f 1)
age=$(echo $line | cut -d ',' -f 2)
gender=$(echo $line | cut -d ',' -f 3)
city=$(echo $line | cut -d ',' -f 4)
if [ $age -gt 30 ] && [ "$city" = "北京" ]; then
echo $line >> $output_file
fi
done < $input_file
请将 large_text_file.txt
替换为实际的大文本文件名,执行脚本后,符合条件的记录会输出到 filtered_records.txt
文件中。