如何替換某些字串?

如何替換某些字串?

我的文字檔案範例:

03/Oct/2016:06:39:50-0500,cd/base/0/48/2.png,206,1514
03/Oct/2016:06:39:50-0500,cd/base/1/46/3.png,206,5796
03/Oct/2016:06:39:50-0500,cd/base/2/45/4.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/3/46/78.png,200,7208
03/Oct/2016:06:39:50-0500,cd/base/4/45/43.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/5/46/8.png,200,7208
...

在本文中,我必須按照base/以下規則替換數字:

if that_number=0 then that_number=5
if that_number=1 then that_number=6
if that_number=2 then that_number=7
if that_number=3 then that_number=8
if that_number=4 then that_number=9
if that_number=5 then that_number=10

想要的結果:

03/Oct/2016:06:39:50-0500,cd/base/5/48/2.png,206,1514
03/Oct/2016:06:39:50-0500,cd/base/6/46/3.png,206,5796
03/Oct/2016:06:39:50-0500,cd/base/7/45/4.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/8/46/78.png,200,7208
03/Oct/2016:06:39:50-0500,cd/base/9/45/43.png,206,2252
03/Oct/2016:06:39:50-0500,cd/base/10/46/8.png,200,7208

知道我該怎麼做嗎?

答案1

在 Perl 中,很容易匹配上下文做加法:

perl -pe 's,base/\K\d+,$& + 5,e' input_file

我們匹配 形式的任何內容,忘記第一部分(直到),並將其餘部分替換為匹配的內容 ( ) 加 5 。base/<numbers>\K$&e

答案2

awk可以利用它對+5每個數字進行操作的事實:

awk -F'/' '{$5+=5 ; print}' OFS='/' input_file

當分別用作輸入 ( ) 和輸出 ( )/的欄位分隔符號時,需要將 5 加到欄位編號 5。-F'/'OFS='/')

請注意,斜槓的位置和數字在這裡至關重要。

答案3

sed會工作:

sed \
    -e 's/base\/1/base\/6/' \
    -e 's/base\/2/base\/7/' \
    -e 's/base\/3/base\/8/' \
    -e 's/base\/4/base\/9/' \
    -e 's/base\/5/base\/10/' \
    -e 's/base\/0/base\/5/'

我認為你必須將「base/0」案例放在最後,否則,5 -> 10 案例也會啟動。

相關內容