Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 数学运算_Bash_Replace_Sed_Terminal_Grep - Fatal编程技术网

Bash 数学运算

Bash 数学运算,bash,replace,sed,terminal,grep,Bash,Replace,Sed,Terminal,Grep,我有一个具有以下结构的文本文件 <h2>Time 455</h2> Random texts may contain numbers <h2>Time 460</h2> Random texts may contain numbers <h2>Time 483</h2> Random texts with numbers <h2>Time 555</h2> Random

我有一个具有以下结构的文本文件

    <h2>Time 455</h2>
Random texts may contain numbers
    <h2>Time 460</h2>
Random texts may contain numbers
    <h2>Time 483</h2>
Random texts with numbers
    <h2>Time 555</h2>
Random texts with numbers
    <h2>Time 550</h2>
Random texts may contain numbers
例如,我想从包含h2时间的每一行的数字中扣除5

因此,最终输出将类似于

    <h2>Time 450</h2>
Random texts may contain numbers
    <h2>Time 455</h2>
Random texts may contain numbers
    <h2>Time 478</h2>
Random texts with numbers
    <h2>Time 550</h2>
Random texts with numbers
    <h2>Time 545</h2>
Random texts may contain numbers

注意:Im使用Mac终端

这是不可靠的,如果随机文本以时间开始,如果锚和时间之间有任何空间,这将不匹配,以及其他问题,但可能:

awk '/^<h2>Time/{$2=$2-5"</h2>"}1' input
或者使用Perl:

perl -pe '/<h2>/ && s/.* \K(\d+)(.*)/$1-5 .$2/e' file
输出


将在任何包含空格的行上发挥其神奇作用,并将该行上最后一个数字减量5,同时保留该行上的任何其他数字。

您尝试过什么吗?sed不是进行算术运算的好选择,您必须显示您在解决问题方面的努力,而不是如果随机文本可能包含数字,请向我们展示一些在您的输入中包含数字的具有代表性的随机文本。时间455符合包含数字的随机文本的条件,所以这可能是你的第二行和第一行吗?如果不是,为什么不明显的是,文本毕竟不是随机的?。请更努力地解释您的需求,并提出一个真正具有代表性的示例输入/输出集。或者首先使用perl-pe's/Time\K\d+/$&-5/enumber@spasic同意,但我试着变得更健壮,只在前面有空格的行中查找一个数字,例如,它将在时间为450的情况下工作。这将在秒数之后删除任何其他HTML标记,例如。如果在数字之前出现任何额外的字段/单词,例如现在的时间是450,那么它将不起作用。2美元是如何分配到这里的?那么$1和$0中有什么?为什么有尾随1?@theonlygusti尾随1相当于{print}。做/^Time/{$2=$2-5;print}也是一样的。没有它,就没有产出。
perl -pe '/<h2>/ && s/.* \K(\d+)(.*)/$1-5 .$2/e' file
<h2>Time 450</h2>
Random texts may contain numbers
<h2>Time 455</h2>
Random texts may contain numbers
<h2>Time 478</h2>
Random texts with numbers
<h2>Time 550</h2>
Random texts with numbers
<h2>Time 545</h1>
Random texts may contain numbers