簡體   English   中英

Bash 在刪除 txt 文件的前 n 行時在行首附加空格

[英]Bash appends space at start of line when removing the first n lines of a txt file

觀察結果

在編寫 function 以從文件中刪除n行的變量 nr 時,output 文件在每行的第一個 position 處有一個額外的空間(在第一行之后)。

例如:

some text
another text
third text
fourth text
fifth text

去:

third text
 fourth text
 fifth text

刪除前n=2行后。

預期結果

本質上,我打算/期望不添加這些額外的空間:

third text
fourth text
fifth text

代碼

執行刪除的 function 包括:

#!/bin/bash
apt_update() {
    source src/hardcoded_variables.txt

    # copy target file
    cp $INPUT_PATH $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE

    # get starting line number
    starting_line=$(<$STARTING_LINE_QUERY_VAR_PATH)
    
    # remove first starting_line lines from the copied target file
    echo -n $(sed "1,${starting_line}d" $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE) > $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE
}
apt_update "$@"

問題

如何防止在 output 文件的第一行之后的每行開頭添加空格?

答案是由 Shawn 作為評論給出的,我使用了sed的復雜方法導致錯誤。 此外,我首先制作了一個文件的副本,並嘗試將sed應用於同一個文件。 當我第一次制作副本,然后從原始文件傳輸到復制文件時,目標文件按預期填充。 因此,找到了一個可行的解決方案:

#!/bin/bash
apt_update() {
    source src/hardcoded_variables.txt

    # copy target file
    cp $INPUT_PATH $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE

    # get starting line number
    starting_line=$(<$STARTING_LINE_QUERY_VAR_PATH)
    
    # remove first starting_line lines from the copied target file
    sed "1,${starting_line}d" $INPUT_PATH > $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE
}
apt_update "$@"

在此解決方案中應用sed之前,我確實需要制作目標副本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM