How can i add each line from a txt file to different files in the same directory?

Hello, this is my first thread here :slight_smile:
So i have a text file that contains words in each line like

abcd
efgh
ijkl
mnop

and i have 4 txt files, i want to add each line to each file, like file 1 gets abcd at the end; file 2 gets efgh at the end ....
I tried with:

cat test | while read -r line; do
for i in *; do
        if [ "$i" == "test" ] ; then
              continue;
        fi
        echo $line >> $i
done
done 

but each time the whole txt is written to each file, i just want each line to each file, not the whole text.

Thanks in advance

Welcome to the forum.

The behaviour you describe is easily understood: you read a line, then echo it to all files in the directory except "test", then read the next line, append to all again, and so forth.

Your request is not quite complete. Does it matter which line goes to which file? What if there's more lines than files / more files than lines?

no it doesn't matter what line goes what file.
for example test has in it:

abcd
efgh
ijkl
mnop

I have 4 files as well in the same directory.
All i want is: abcd goes to the end of file 1
efgh goes to the end of file 2
ijkl goes to the end of file 3
mnop goes to the end of file 4

Thanks

Try this slight modification to your attempt:

for i in file[1-4]
  do    read -r line
        if [ "$i" == "test" ] 
          then  continue
        fi
        echo $line >> $i
  done < test
1 Like

you're amazing man, it worked.
Thank you sooo much.

If your shell offers "extended pattern matching" with the extglob shell option, you could avoid the if construct in your loop:

shopt -s extglob
ls -la !(test)

will list all files in your current working directory except test .

the first correction you gave me solved my issue, i really appreciate brother. you're amazing.