2013-03-12 63 views
1

是有可能從二進制文件MYFILE替換字節從一個特定位置到另一個DD在一個循環或正在使用另一個命令更舒適?如何替換/與殼替換字節以二進制文件

的想法是在形勢2位置與塊位置1在一個循環中替換塊

僞代碼

@ l = 0 

    while (l <= bytelength of myfile) 
     copy myfile (from position1 to A+position1) myfile from (position2 to B+position2) 
     @ position1 = position1+steplength 
     @ position2 = position2+steplength 
     @ l = l+steplength 

    end 
+0

儘管可能,我不會使用shell命令語言來處理這種類型的文件。使用對此類文件I/O具有更好支持的語言。無論哪種情況,你是在'位置2'覆蓋字節,還是隻是重新排列文件內的字節順序? – chepner 2013-03-12 14:31:53

+0

我想覆蓋它們,如果可能的話... – MichaelScott 2013-03-12 14:47:41

+0

可能重複[如何用dd覆蓋二進制文件的某些字節?](http://stackoverflow.com/questions/7290816/how-to-overwrite-some-字節對的一二進制文件與 - DD) – user2284570 2014-01-07 22:50:22

回答

0

的代碼在一個文本文件中的以下行會做大約什麼(我覺得)你所要求的:從一個位置複製到另一個文件,但替換塊一個位置的字節與另一個位置的一個塊;它按要求使用dd。但是,它確實會創建一個單獨的輸出文件 - 無論「輸入」塊是在「替換」塊之前還是之後出現,都必須確保沒有衝突。請注意,如果A和B之間的距離小於要被替換的塊的大小,它將不會執行任何操作 - 這會導致重疊,並且不清楚您是否希望重疊區域中的字節爲「 A「或」A的副本的開始「。

將其保存在名爲blockcpy.sh的文件中,並將權限更改爲包括execute(例如chmod 755 blockcpy.sh)。與

./blockcpy.sh inputFile outputFile from to length 

注意運行它的「從」和「到」補償對基礎爲零:所以如果你想複製起始於文件的起始字節,from參數爲0

這裏是文件內容:

#!/bin/bash 
# blockcpy file1 file2 from to length 
# copy contents of file1 to file2 
# replacing a block of bytes at "to" with block at "from" 
# length of replaced block is "length" 
blockdif=$(($3 - $4)) 
absdif=${blockdif#-} 
#echo 'block dif: ' $blockdif '; abs dif: ' $absdif 
if [ $absdif -ge $5 ] 
    then 
    # copy bytes up to "to": 
    dd if=$1 of=$2 bs=$4 count=1 status=noxfer 2>0 
    # copy "length" bytes from "from": 
    dd bs=1 if=$1 skip=$3 count=$5 status=noxfer 2>0 >> $2 
    # copy the rest of the file: 
    rest=$((`cat $1 | wc -c` - $4 - $5)) 
    skip=$(($4 + $5)) 
    dd bs=1 if=$1 skip=$skip count=$rest status=noxfer 2>0 >> $2 
    echo 'file "'$2'" created successfully!' 
    else 
    echo 'blocks A and B overlap!' 
fi 

2>0的「「尼克斯魔力」抑制從stderr輸出其中在(類型:「16+0 records in」)的輸出,否則顯示出來。