【问题标题】:Parse From Text File into String output从文本文件解析成字符串输出
【发布时间】:2021-03-27 22:45:33
【问题描述】:

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

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

我正在尝试编写一个 sed 脚本,该脚本将读取文本文件,然后以格式输出 ",现在是 岁。"

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

【问题讨论】:

    标签: linux bash sed


    【解决方案1】:

    我知道我需要设置 IFS=

    我不明白为什么有必要这样做。据我所知sed 根本不使用IFS

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

    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.
    

    【讨论】:

    • 如果用数字代替性别的“M/F”会发生什么?喜欢在公司工作几年?所以你添加了 13.5、10.2、11.8?这将如何改变,因为我假设您现在不能搜索和使用 $ 年龄和年份?抱歉,我只是想弄清楚 sed,因为我认为 $ 不能用于多个案例。
    • $ 刚刚结束。我用它追加文本到每一行。如果在中间添加列,$ 部分不会发生任何变化。如果在末尾添加列,则必须以另一种方式插入 years old now,例如通过替换 ,.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-22
    相关资源
    最近更新 更多