2017-09-27 62 views
0

我想在使用shell腳本的特定文本之後插入一個隨機數。我可以生成一個隨機數(32個字符):在一個文件?:如何在使用sed的文本之後插入隨機數

cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1 

如何插入文本後,這個隨機數(32_char_random_number)(例如,「字母」

sed '/\balphabet \b/& 32_char_random_number/' file 
+0

[MCVE(https://stackoverflow.com/help/mcve)請 – Thor

回答

1

假定您蘭特號碼分配給$char_random_number

char_random_number=$(cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 32 | head -n 1) 

而且你可以使用雙引號來訪問變量,

sed "s/\(alphabet\)/\1$char_random_number/g" file 
+0

運行時,你或許應該加上-r的sed –

+0

與-r選項,擴展正則表達式允許的。但不需要添加我的答案。 :) – CWLiu

+0

它會替換\ 1沒有-r? –

0

穩健AWK解決方案:

樣品input.txt內容:

Lorem ipsum dolor alphabet sit amet, consectetuer adipiscing elit alphabet. Aenean commodo ligula eget dolor. 
Aenean massa. Cum sociis natoque penatibus et alphabet magnis dis parturient montes, nascetur ridiculus mus. 
Donec quam felis, alphabet ultricies nec, pellentesque eu, alphabet pretium quis, sem. Nulla consequat massa quis enim. 
Donec pede justo, fringilla no alphabet vel, aliquet nec, alphabet vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. 
Nullam dictum felis eu pede alphabet mollis pretium. 
Integer tincidunt, alphabet. Cras dapibus. 

的工作:

rnum=$(< /dev/urandom tr -dc [[:alnum:]] | head -c 32) 
awk -v rnum="$rnum" '{ gsub(/\<alphabet\>/,"& "rnum) }1' 

輸出:

Lorem ipsum dolor alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 sit amet, consectetuer adipiscing elit alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5. Aenean commodo ligula eget dolor. 
Aenean massa. Cum sociis natoque penatibus et alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 magnis dis parturient montes, nascetur ridiculus mus. 
Donec quam felis, alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 ultricies nec, pellentesque eu, alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 pretium quis, sem. Nulla consequat massa quis enim. 
Donec pede justo, fringilla no alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 vel, aliquet nec, alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. 
Nullam dictum felis eu pede alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5 mollis pretium. 
Integer tincidunt, alphabet g9vgamG[slhPKJgOxqphM[KFOdL1qDo5. Cras dapibus. 
+0

謝謝,明天再確認。 – AP70

相關問題