简体   繁体   中英

sed randomized last digits using expression

I need to parse a file and randomized the last digits for a given string when the pattern is found.

I am able to perform the desired result when using a simple case but it fails for a more complex case.

I am wondering what is wrong with the second case.

This example here works.

echo 'AB111-1-13' | sed 's/\(AB111\)-\([0-9]*\)-\([0-9]*\)/echo \1-\2-$(echo \3*$RANDOM | bc )/ge'

But this one doesn't work.

echo '<http://name/link#AB111-1-13>' | sed 's/\(AB111\)-\([0-9]*\)-\([0-9]*\)/echo \1-\2-$(echo \3*$RANDOM | bc )/ge'

Any ideas?

EDIT This is the error message when trying to run the second example.

sh: -c: line 0: syntax error near unexpected token newline' sh: -c: line 0: '

The GNU sed e flag executes the pattern space as a shell command.

In your first example your pattern space starts as AB111-1-13 and becomes echo AB111-1-$(echo 13*$RANDOM | bc ) which is a valid shell command and gets executed. (I should point out that bc is entirely unnecessary here as the shell can perform integer arithmetic just fine by itself echo $((13 * RANDOM)) .)

But in your second example you pattern space starts as <http://name/link#AB111-1-13> and becomes <http://name/link#echo AB111-1-$(echo 13*$RANDOM | bc )> which is very much not a valid shell command and so, presumably, you get a shell error (would have been good of you to include it in the question though) when it tries to get executed.

So don't use sed for this. Use something that can evaluate arbitrary expressions like awk or perl or python , etc.

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