简体   繁体   中英

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:

...
12
13
7
15
16
...

My current code is the following, but the sed command does not work well,

$sudo seq 1 100 | sed -e 's/$?{%7==0}/7/g' > check.txt

How should I write math operations in sed ?

You can't do arithmetic operations in sed, but you can implement them to some extent with existing features, like:

seq 100 | sed '7~7s/.*/7/'

With awk that would be:

awk 'BEGIN { for (i=1;i<=100;i++) print i%7?i:7 }'

Sed can't do arithmetics, but Perl can. It can also do a sequence, so no need for seq and a pipe:

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. -l adds a newline to each 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM