首页 > 解决方案 > 从文本文件解析成字符串输出

问题描述

所以我有一个名为 employees.txt 的文本文件,看起来像这样......

Billy Madderson, M, 34
Allison McGever, F, 32
Bill Nye, M, 35

我正在尝试编写一个 sed 脚本,该脚本将读取文本文件,然后以“<name> 是<gender>,并且现在<age> 岁”的格式输出它。

我知道我需要设置 IFS=,但我不知道如何将信息放在字符串中。非常感谢任何输入!

标签: linuxbashsed

解决方案


我知道我需要设置 IFS=

我不明白为什么这是必要的。据我所知sed根本不用IFS

将第一个替换为,, is a/ Mby F/ manwoman第二个,替换为and is等等。唯一棘手的部分是仅替换第二列中的 / 而不是您遇到的第M一个/ 。幸运的是,在第二列之后没有字母了,这样就简化了。FMF

sed 's/, M/ is a man/;s/, F/ is a woman/;s/, /, and is /;s/$/ years old now./' file

对于您的示例,输出为

Billy Madderson is a man, and is 34 years old now.
Allison McGever is a woman, and is 32 years old now.
Bill Nye is a man, and is 35 years old now.

推荐阅读