简体   繁体   English

逐行读取时向文件添加行

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

Is it possible to appned line(s) to file while reading a file using bash loop?是否可以在使用 bash 循环读取文件时将行添加到文件中? Below the code that I am reading the file and pseudocode what I want to achieve.在我正在读取文件和伪代码的代码下方,我想要实现的目标。 I wanted to be done at the same file and not creating a new one and then copy the contents to the original one我想在同一个文件中完成,而不是创建一个新文件,然后将内容复制到原始文件

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

The simplest solution is by sed :最简单的解决方案是sed

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

A simple any version sed :一个简单的任何版本sed

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

Write all of your text out to a second file, then copy that tempfile over your original file.将所有文本写入第二个文件,然后将该临时文件复制到原始文件上。

Also, I know you said it was psuedo-code, but I went ahead and fixed some of the other typos/syntax errors you had in your script.另外,我知道您说这是伪代码,但我继续修复了您在脚本中遇到的其他一些拼写错误/语法错误。 The following does exactly what you need.以下正是您需要的。

#!/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