Home > Enterprise >  Add line to file while reading line by line
Add line to file while reading line by line

Time:08-24

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"

CodePudding user response:

The simplest solution is by sed:

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

CodePudding user response:

A simple any version sed:

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

CodePudding user response:

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}

  • Related