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

aki*_*raj 3 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_file2.txt
    echo "$line" >> test_file2.txt
done <"$file"
echo "completed"
Run Code Online (Sandbox Code Playgroud)

该脚本将“ Test”写入test_file2.txt,但不将“ legendary”或test_file1中的行写入test_file2。

有人可以帮忙吗?

谢谢。

DAX*_*lic 5

只需直接使用文件,而不是先将其读取到数组中即可;这样做将您更改
done <"$file"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"
Run Code Online (Sandbox Code Playgroud)

  • 当然,编写 awk 脚本会更有效 - 用 C 编写本机应用程序会更有效 :) 如果这个脚本要处理数千行,那么我同意,它可能应该重构。在这种情况下,我只是假设(缺少信息的 bc)没有如此严格的性能限制,因此恕我直言,最好向提问者展示他自己代码的失败部分,而不是给他一个完整的新代码片段(甚至可能在一种不同的语言)这可能很难理解。尽管如此,还是感谢补充说明! (2认同)