Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read line by line and write in another file shell script

Tags:

shell

I have a file called "test_file1". I want to read each line of this file and write it to another file called "test_file2". Both of these files are in the same directory.

I tried

#!/bin/sh
# My first Script
echo "Hello World!"
file=$(<test_file1.txt)
echo "Test" >> test_file2.txt 
while IFS= read -r line;do
    echo -e "legendary" >> test_file2.txt
    echo "$line" >> test_file2.txt
done <"$file"
echo "completed"

The script writes "Test" into test_file2.txt but does not write 'legendary' or the lines in test_file1 into test_file2.

Can someone please help.

Thank you.

like image 624
akilesh raj Avatar asked Dec 14 '25 15:12

akilesh raj


1 Answers

Just use the file directly instead of first reading it into an array; to do that change your
done <"$file" to done < "test_file1.txt"

#!/bin/sh
# My first Script
echo "Hello World!"
echo "Test" >> test_file2.txt 
while IFS= read -r line;do
    echo -e "legendary" >> test_file2.txt
    echo "$line" >> test_file2.txt
done < "test_file1.txt"
echo "completed"
like image 160
DAXaholic Avatar answered Dec 19 '25 06:12

DAXaholic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!