【问题标题】:How to read a file and copy from one file to another file in shell script如何在shell脚本中读取文件并从一个文件复制到另一个文件
【发布时间】:2013-11-01 16:23:33
【问题描述】:

如何在 shell 脚本中读取文件并从一个文件复制到另一个文件:

#!/bin/csh -f
echo ---file.txt---
cat file.txt

echo ######## file.text is opened ########
#set file_1="export/home/caratins/trial/file.txt"
while read line
do
echo "$line"
cp file.txt files

done<file.txt

实际上有一个文件夹trial,里面有4个文本文件。我想打开一个文件-'file.txt'。在 file.txt 里面有 3 个文件名:test1.txt、test2.txt、test3.txt。我的工作是使用 file.txt 文件,我已经阅读了所有 3 个文件名并将其复制到另一个文件夹。所以为此我必须打开file.txt,读取文件并打印3个文件,只复制这3个文件而不是完整文件夹并将这3个文件复制到同一目录中的另一个文件夹'files'。

【问题讨论】:

  • 请尝试改进您的解释并提供一些testN.txt示例。
  • cat filen1.txt &gt;&gt; file2.txt 使用此命令可以简单地从一个文件复制到另一个文件。

标签: linux shell


【解决方案1】:

试试这个, 这里 test1 是你的源文件夹,它将包含你的文件, 并且 test2 是目标文件夹,您将在阅读后移动文件..

#!/bin/sh
cd test1;
echo "list of files:";
ls;
for filename in *;
do echo "file: ${filename}";
echo "reading..."
exec<${filename}
value=0
while read line
do
   #value='expr ${value} +1';
   echo ${line};
done
echo "read done for ${filename}";
cp ${filename} ../test2;
echo "file ${filename} moved to test2"; 
done 

或者你可以试试这个...

ls;
echo "reading main file...";
filenames="filenames";
exec<${filenames}
while read name
do
  echo "file: ${name}";
  echo "reading..."
  cd test1;
exec<${name}
value=0
while read line
do
#value='expr ${value} +1';
echo ${line};
done
echo "read done for ${name}";
cp ${name} ../test2;
cd ..;
echo "file ${file} moved to test2"; 
done 

你...

【讨论】:

  • 它是正确的,但它是复制完整的 test1 文件夹而不是 3 个文本文件。
【解决方案2】:

如果你想复制整个文件,那么

cat filename >> newfilename

三个文件

cat file1.txt file2.txt file3.txt >>file.txt

如果你想逐行复制,那么

while IFS= read -r line
do
echo "$line"
echo -e "$line\n" >>newfilename

done <"filename"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2019-02-10
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多