簡體   English   中英

逐行讀取時向文件添加行

[英]Add line to file while reading line by line

是否可以在使用 bash 循環讀取文件時將行添加到文件中? 在我正在讀取文件和偽代碼的代碼下方,我想要實現的目標。 我想在同一個文件中完成,而不是創建一個新文件,然后將內容復制到原始文件

#!/bin/bash
input="/path/to/txt/file"
while read -r line
do
  if [ line == 'test' ]; then
  # Append some text to next line 
done < "$input"

最簡單的解決方案是sed

sed -r 's/(line)/\1\nNew added line\n/g' /path/to/txt/file

一個簡單的任何版本sed

sed '/test/ a\
Text appended
' /path/to/txt/file

將所有文本寫入第二個文件,然后將該臨時文件復制到原始文件上。

另外,我知道您說這是偽代碼,但我繼續修復了您在腳本中遇到的其他一些拼寫錯誤/語法錯誤。 以下正是您需要的。

#!/bin/bash
input="input.txt"
outfile="/tmp/outfile.txt"
extra_text="foobarwaz"

echo '' > ${outfile}

while read -r line ; 
do
  echo "${line}" >> ${outfile}
  if [ "${line}" == 'test' ]; then
    echo ${extra_text} >> ${outfile}
  fi
      
done < "$input"

cp ${outfile} ${input}

暫無
暫無

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

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