0

I have file test.txt and file contains some lines So i have to add "done" at the end of the word once the verification is done, Initial text file

test.txt

abc

bcd

cde

expected output

test.txt

abc DONE

bcd DONE

cde DONE

Below is the code i am using

 k=0
 for i in `cat test.txt` 
 do 
 if [[ $k -le 5 ]];
 then
 echo $i >> XYZ
 k=`expr $k + 1`
 sed  '/$i/a "DONE"' test.txt
 fi;
 done

But i couldn't see any changes in test.txt. Any idea how to do

Rajesh
  • 13
  • 1
  • 7
  • See [this](https://stackoverflow.com/questions/13799789/expansion-of-variable-inside-single-quotes-in-a-command-in-bash-shell-script) for dealing with expansions within single quotes. See [this](https://stackoverflow.com/questions/12696125/sed-edit-file-in-place) for `sed` in-place replacement. – Jedi Jun 27 '17 at 14:59

1 Answers1

1

You had two major flaws; bash variables are preserved literally within single quotes and you did not use sed's in-place replacement -i flag.

#!/bin/bash
k=0
for i in `cat test.txt`
do
        if [[ $k -le 5 ]];
        then
                echo "$i" >> XYZ
                k=`expr $k + 1`
                sed -i 's/'"$i"'/'"$i"' DONE/' test.txt
        fi;
done

Be careful when editing files simultaneously while reading through them.

Jedi
  • 3,088
  • 2
  • 28
  • 47