[英]How to replace a number with sed command if number%7==0 in bash?
I am trying to create a file that contains all numbers between 1 and 100, each number in a single line, but with all multiples of 7 substituted by 7:我正在尝试创建一个文件,其中包含 1 到 100 之间的所有数字,每个数字都在一行中,但所有 7 的倍数都被 7 替换:
...
12
13
7
15
16
...
My current code is the following, but the sed
command does not work well,我当前的代码如下,但sed
命令不能正常工作,
$sudo seq 1 100 | sed -e 's/$?{%7==0}/7/g' > check.txt
How should I write math operations in sed
?我应该如何在sed
编写数学运算?
You can't do arithmetic operations in sed, but you can implement them to some extent with existing features, like:您不能在 sed 中进行算术运算,但您可以使用现有功能在一定程度上实现它们,例如:
seq 100 | sed '7~7s/.*/7/'
With awk that would be:使用 awk 将是:
awk 'BEGIN { for (i=1;i<=100;i++) print i%7?i:7 }'
Sed can't do arithmetics, but Perl can. Sed 不能做算术,但 Perl 可以。 It can also do a sequence, so no need for seq
and a pipe:它也可以做一个序列,所以不需要seq
和管道:
perl -le 'print $_ % 7 ? $_ : 7 for 1 .. 100'
It uses the ternary operator ?:
which evaluates the condition ( $_ % 7
here, ie the modulo) and returns the second parameter if it's true, or the third parameter otherwise.它使用三元运算符?:
评估条件(此处$_ % 7
,即模数),如果为真则返回第二个参数,否则返回第三个参数。 -l
adds a newline to each print
. -l
为每个print
添加一个换行符。
我喜欢sed
,但我认为这更像是awk
的工作:
seq 1 100 | awk '{ if ($1 % 7 == 0) { print 7; } else { print $0; } }'
其实普通的bash
也可以处理这个:
for i in $(seq 1 100); do (( i % 7 )) && echo $i || echo 7; done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.