逐行读取并写入另一个文件shell脚本

逐行读取并写入另一个文件shell脚本,shell,Shell,我有一个名为“test_file1”的文件。我想读取此文件的每一行,并将其写入另一个名为“test_file2”的文件。这两个文件都在同一目录中 我试过了 #!/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_file1”的文件。我想读取此文件的每一行,并将其写入另一个名为“test_file2”的文件。这两个文件都在同一目录中

我试过了

#!/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"
#/垃圾箱/垃圾箱
#我的第一个剧本
回声“你好,世界!”
file=$(>test_file2.txt
当IFS=读取-r行时;执行
echo-e“legendary”>>test_file2.txt
echo“$line”>>test_file2.txt

完成只需直接使用该文件,而不是首先将其读入数组;为此,请更改您的
done>test_file2.txt
当IFS=读取-r行时;执行
echo-e“legendary”>>test_file2.txt
echo“$line”>>test_file2.txt
完成<“测试文件1.txt”
回显“已完成”

Hi DAXaholic,谢谢。现在可以正常工作了。!!在
done
之后执行一次重定向要比在循环中重复打开和关闭文件有效得多。最好还是用srmpe Awk脚本替换它;读写这样的行的shell循环通常是一种反模式。当然是这样如果这个脚本要处理数千行代码,那么我同意,它可能应该被重构。在这种情况下,我只是假设(缺乏信息的bc)没有这样严格的性能约束,因此,我认为最好向提问者展示他自己代码中失败的部分,而不是给他一个可能很难理解的完整的新代码片段(甚至可能是另一种语言)。尽管如此,附加注释仍需thx!
#!/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"