Bash - 如何將字串新增至文字檔案的開頭而不讀取全部內容?

Bash - 如何將字串新增至文字檔案的開頭而不讀取全部內容?

我試圖在名為“test.txt”的文字檔案之前插入一個字串“hello world”,我已經使用sed 執行此操作,但不幸的是“sed 命令”殺死了我的記憶,因為它讀取了整份文件。

我的檔案包含 1GB 大小的文本,而我的記憶體只有 512 MB。我該怎麼做?

echo --insert-before "hello world" >> test.txt

或者我必須使用哪個運算符來插入它,如下所示:

echo "hello world" << test.txt

或另一個想法?

注意:在末尾插入文字的運算>>子工作正常,它不會殺死我的記憶,但我需要在文件的開頭反向執行此操作,而不覆蓋我的文字檔案的內容,沒有新行。

這是我使用的實際程式碼:

echo "hello world" > test.txt;
echo "the large content that size is 1gb" >> test.txt;
sed -i ':a;N;$!ba;s/\n//g' test.txt;

答案1

您聲明您使用的命令順序是:

echo "hello world" > test.txt;
echo "the large content that size is 1gb" >> test.txt;
sed -i ':a;N;$!ba;s/\n//g' test.txt;

我假設這些命令實際上是:

echo "hello world" > newfile;
cat test.txt >> newfile;            # assuming the file with 1GigaByte was test.txt

您抱怨 sed 命令,該命令僅用於刪除換行符(從您的描述中)。

tr不使用(太多)內存的情況下也可以完成相同的操作:

echo "hello world" > newfile;
cat test.txt | tr -d '\n' >> newfile

並將newfile有一份 test.txt 的副本,前面加上「hello world」。

答案2

sed不要使用太多內存。但是作業系統可能正在緩存磁碟。因此使用nocache可能會有所幫助(如果磁碟足夠快,或者您沒有多次讀取相同的資料)。和/或使用--unbuffered選項sed(以便sed依賴確實使用盡可能少的記憶體)。

另外,也不能有回顯選項,這>>是由 shell 完成的,而不是由指令完成的。它告訴 shell 將命令的標準輸出附加到檔案中。

正如@Kusalananda 所說,你的sed腳本效率不高。我可能只會使用貓。

uncache cat "<(echo the_prefix)" old_file_name > new_file_name
rm old_file_name
mv -T new_file_name old_file_name #note not all `mv`s have the `-T` option, it can unsafely be left out.

答案3

來點簡單一點的怎麼樣?

cat <<_eof_ > file
Hello world!
$(cat file)
_eof_

或使用ed

echo '0a
your text here
.
w' | ed some_file

答案4

如果這正在扼殺你的記憶:

sed -i ':a;N;$!ba;s/\n//g' "test.txt"

然後,要刪除換行符但一次只讀取一個換行符,請嘗試:

{
    printf "hello world"  # with no newline
    while IFS= read -r line || [ -n "$line" ]; do
        printf "%s" "$line"
    done < test.txt
    echo ""          # add a newline to the end of the file
} > test.txt.tmp && mv test.txt{.tmp,}

在正常情況下,這會比 sed 慢一點,但你的情況不同尋常。

相關內容