简体   繁体   中英

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? 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 -r 's/(line)/\1\nNew added line\n/g' /path/to/txt/file

A simple any version 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM