【问题标题】:Replace a capture group with the output from a script用脚本的输出替换捕获组
【发布时间】:2021-11-27 17:14:17
【问题描述】:

我正在尝试用完整的书面文字形式替换某个文本中的所有数字。

例如,如果输入是

this university has 9123 students
one of its departments has 2315 students

输出将是

this university has nine thousand one hundred and twenty three students
one of its departments has two thousand three hundred and fifteen students

我有一个名为num2words.sh 的脚本,它可以将像 9123 这样的数字转换为其单词形式。我想用这个脚本替换一个名为file1.txt 的文件中的所有数字。我一直在尝试使用 sed,但我无法让它工作。到目前为止,我有这个,

cat file1.txt | sed -e "s/\([0-9]\+\)/)/$(./num2words.sh \1)"

我猜 \1 没有正确传递。任何人都可以为此提供解决方案吗?使用sed 会更好,但我也愿意接受awkperl 的解决方案。

【问题讨论】:

  • $() 在解析命令行时被替换,而不是在内部被 sed 替换。

标签: linux string bash sed


【解决方案1】:

这可能对你有用(GNU sed):

sed -E 's#[0-9]+#$(./num2words.sh &)#g;T;s/.*/echo "&"/e' file

将数字输入$(./num2words.sh x),其中x 是一个数字。

如果没有替代,则退出。

将整行双引号括起来,然后使用e 标志将其回显以评估模式空间。

注意可能会有不想要的副作用。

【讨论】:

    【解决方案2】:

    使用 perl,

    perl -pe 's#[0-9]+#`./num2words.sh $&`#eg' file1.txt
    

    【讨论】:

    • 虽然我会在 perl 中重写脚本以避免每次匹配都执行一个程序。
    • 我在运行此命令时收到一个以 Backticks found where operator expected at -e line 1, at end of line 开头的错误
    • 我使用perl -pe 's/([0-9]+)/`\.\/num2words.sh $&`/eg'解决了上述错误
    • @qk2905 脚本路径中的 / 令人困惑;我的错。见编辑。
    猜你喜欢
    • 2018-06-09
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多