D
D
Dmitry Kuzmin2015-06-15 12:53:33
linux
Dmitry Kuzmin, 2015-06-15 12:53:33

How does SED work with variables?

I execute the command

sed -i "s/\(\([^,]\+,\)\{9\}\)/\1$((RANDOM%1000000+8243678))/" file.txt

According to it, he puts a random number after the 9th comma in each line of the file.
But for some reason, apparently to understand which I do not have enough knowledge, Sed, instead of getting the value of the variable RANDOM% 1000000 + 8243678 for each line, takes and puts down the same (apparently the first received) value of this variable. Perhaps this is a feature of how Sed works with the -i option. Who can tell whether it is possible through Sed in this case to implement and how to set the value of the RANDOM variable for each unique line.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Konkase, 2015-06-15
@Konkase

The RANDOM function is executed once when it is called, sed calls this function once when opening a file, so you need to loop it, like this:

cat file.txt | while read line; do echo $line | sed "s/\(\([^,]\+,\)\{9\}\)/\1$((RANDOM%1000000+8243678))/"; done

S
Sergey N, 2015-06-18
@Albibek

SED does not work with this variable in any way. When processing a command, the shell replaces the variable with a value that has already been calculated before even running sed itself.
As a result, sed does something like:
Konkase is right in advising you to use a loop.

K
Konstantin, 2015-06-15
@fallen8rwtf

you have one thread running and it contains one variable $RANDOM
try to make a loop for each line with the assignment of this variable. in fact, for each cycle it will be generated anew

V
Vladimir, 2019-06-25
@mole2

the variable is taken in curly braces
example
sed -i "/${controlnumber}/d" ./000

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question