【问题标题】:Reading input file and inserting text into output file读取输入文件并将文本插入输出文件
【发布时间】:2016-01-22 14:45:16
【问题描述】:

我有一个名为“namelist.txt”的输入文件,其中包含电子邮件地址:

user1@domain.com
user2@domain.com
user3@domain.com

我正在尝试从此输入文件中读取地址并将它们的值插入到输出文件 (newfile.txt) 中,该文件应为:

user "user1@domain.com" with pass"pass" is "user1@domain.com" here
user "user2@domain.com" with pass"pass" is "user2@domain.com" here
user "user3@domain.com" with pass"pass" is "user3@domain.com" here

我最接近的是使用 awk:

awk '{print "user $0 there with pass"pass" is user $0 here"}' < namelist.txt > newfile.txt

然而,这会打印以下内容:

user $0 there with pass is user $0 here 
user $0 there with pass is user $0 here
user $0 there with pass is user $0 here

这不会打印变量值或“通过”值。

我不知道我哪里错了,或者我是否在正确的轨道上,所以任何建议和/或指针都将不胜感激。

编辑:

使用:

awk '{print "user \""$0"\" there with pass \"pass\" is user \""$0"\" here}' file

在 Ubuntu (14.04.2 LTS) 上产生以下输出:

" 这里的通行证 "pass" 是用户 "user1@domain.com
“通过“pass”的here是用户“user2@domain.com
" 通行证 "pass" 的这里是用户 "user3@domain.com

上述代码在 UNIX 终端中运行良好,但在 Ubuntu 和 Raspberry Pi 中却不行。

我很困惑为什么发行版之间存在差异。

【问题讨论】:

    标签: bash awk substitution


    【解决方案1】:

    $ 变量需要在引号之外,并且您需要转义要查看的引号。

    awk '{print "user \""$0"\" there with pass\"pass\" is user \""$0"\" here"}' file
    
    user "user1@domain.com" there with pass"pass" is user "user1@domain.com" here
    user "user2@domain.com" there with pass"pass" is user "user2@domain.com" here
    user "user3@domain.com" there with pass"pass" is user "user3@domain.com" here
    

    【讨论】:

    • 感谢您的快速回复。我想我可能还有另一个问题。当我在在线 unix 终端中尝试您的答案时,它可以完美运行。但是,当我在 Ubuntu(或 Raspi)上尝试时,我得到了不同的结果:“ heree with pass”pass” is user “user1@domain.com” heree with pass“pass” is user “user2@domain.com” heree with pass “通过”是用户“ user3@domain.com
    • 在帖子中显示您在格式化文本中遇到的任何问题,无法阅读和猜测您在 cmets 中编写的内容的格式。
    • 对不起。我已经编辑了原始帖子以反映我使用您的答案的尝试。
    • 您的输入文件是在 Windows 上创建的,因此行尾的 control-M 已损坏。在上面运行dos2unix 或类似的。
    • 对于 DOS 文件启用可以在您的代码中放置 { sub(/\r$/,"") } 子句,或者如果使用 GAWK,您可以使用 RS ="\r?\n" -- 我在为工作而构建的脚本上执行此操作,因为我想干净地处理 DOS 和 Unix 文件。
    【解决方案2】:

    您已将文本 $0 包含在文字字符串中,但无论如何,在将输入数据插入到某些格式化字符串以进行输出时,如果您使用 printf 而不是 print,将来通常最清晰且最容易增强:

    $ awk '{printf "user \"%s\" there with pass \"pass\" is user \"%s\" here\n", $0, $0}' file
    user "user1@domain.com" there with pass "pass" is user "user1@domain.com" here
    user "user2@domain.com" there with pass "pass" is user "user2@domain.com" here
    user "user3@domain.com" there with pass "pass" is user "user3@domain.com" here
    

    并且不要将输入重定向与 awk 一起使用,因为这会删除脚本访问输入文件名的能力。 awk 完全可以自己打开文件。

    【讨论】:

    • 感谢您的洞察力。我非常重视它。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 1970-01-01
    相关资源
    最近更新 更多