2011-02-17 48 views
1

我有這個文件elif的條件語句:沒有工作

The number is %d0The number is %d1The number is %d2The number is %d3The number is %d4The number is %d5The number is %d6The... 
The number is %d67The number is %d68The number is %d69The number is %d70The number is %d71The number is %d72The.... 
The number is %d117The number is %d118The number is %d119The number is %d120The number is %d121The number is %d122 

我想填充它喜歡:

The number is %d0 The number is %d1 The number is %d2 The number is %d3 The number is %d4 The number is %d5 The number is %d6 
The number is %d63 The number is %d64 The number is %d65 The number is %d66 The number is %d67 The number is %d68 The number is %d69 
d118The number is %d119The number is %d120The number is %d121The number is %d122The number is %d123The number is %d124The 

請告訴我如何通過shell腳本 我正在做Linux的

+0

順便說一句,你只有在第一個選擇中有一個倒退。 – 2011-02-17 09:41:51

+1

你在用什麼外殼?慶典? – marcog 2011-02-17 09:41:54

回答

1

編輯:

氏S單命令管道應該做你想要什麼:

sed 's/\(d[0-9]\+\)/\1 /g;s/\(d[0-9 ]\{3\}\) */\1/g' test2.txt >test3.txt 
#     ^three spaces here 

說明:

對於繼「d」的數字每個序列,其後添加三個空格。 (我會用「X」來表示空格。)

d1 becomes d1XXX 
d10 becomes d10XXX 
d100 becomes d100XXX 

現在(分號之後的部分),捕捉每一個「d」和接下來的三個字符必須是數字或空格,並將其輸出但不任何空間之外。

d1XXX becomes d1XX 
d10XXX becomes d10X 
d100XXX becomes d100 

如果你想爲你似乎在您的樣本數據顯示包線,然後做這個:

sed 's/\(d[0-9]\+\)/\1 /g;s/\(d[0-9 ]\{3\}\) */\1/g' test2.txt | fold -w 133 >test3.txt 

您可能需要調整fold命令的參數,使之出來吧。

有沒有必要ifgrep,循環等

原來的答覆:

首先,你真的需要說哪個殼您正在使用,但因爲你有eliffi,我假設它是伯恩派生的。

基於這個假設,你的腳本沒有意義。

  • ifelif的括號是不必要的。在這種情況下,他們創建了一個無用的子shell。
  • ifelifsed命令說:「如果該模式被發現,複製保留空間(它是空的,順便說一句),以模式空間和輸出,並輸出所有其他線路。
  • 第一sed命令將始終爲爲真,因此elif將永遠不會執行。sed始終返回true,除非出現錯誤。

這可能是你的原意:

if grep -Eqs 'd[0-9]([^0-9]|$)' test2.txt; then 
    sed 's/\(d[0-9]\)\([^0-9]\|$\)/\1 \2/g' test2.txt >test3.txt 
elif grep -Eqs 'd[0-9][0-9]([^0-9]|$)' test2.txt; then 
    sed 's/\(d[0-9][0-9]\)\([^0-9]\|$\)/\1 \2/g' test2.txt >test3.txt 
else 
    cat test2.txt >test3.txt 
fi 

但我不知道,如果一切可以通過類似這樣一行代碼代替:

sed 's/\(d[0-9][0-9]?\)\([^0-9]\|$\)/\1 \2/g' test2.txt >test3.txt 

因爲我不知道什麼test2.txt看起來像,這只是猜測的一部分。