[英]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.