How to add a word to the end of a line in bash?

584 views Asked by At

In the following code we are adding words one under the other. I want to add at the end of a line

doc_in=$1 #document to read
main_d=$2 #dictionary of words   
ignored_d=$3 #other dictionary of words    
doc_out=$4 #document to write

word="example"        

function consult_user() { 
    echo "word not found:[$word] Accept (a) - Discard (i) - Replace (r):"

    read opt
    if [ $opt == "a" ]
    then    
        #Here I want to add at the end of a line and not "echo"
        echo $word >>$doc_out # me agrega todo con un \n 
    elif [ $opt == "i" ]
    then
        echo $word >>$ignored_d
    else 
        read new_w
        echo $new_w >>$doc_out
    fi
}

consult_user
1

There are 1 answers

1
Sriharsha Kalluru On

You can use sed command to get it done.

   sed -i -e "s/$/$word/" $doc_out

[root@client1 ~]# word=example
[root@client1 ~]# doc_out=test
[root@client1 ~]# cat $doc_out
Test Line1
Test Line2
Test Line3
Test Line4
[root@client1 ~]# sed -e "s/$/ $word/" $doc_out
Test Line1 example
Test Line2 example
Test Line3 example
Test Line4 example