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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19540903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:09:59  来源:igfitidea点击:

How to read a file and copy from one file to another file in shell script

linuxshell

提问by user2911160

How to read a file and copy from one file to another file in shell script:

如何在 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

Actually one folder trial is there, inside trial folder 4 text files are there. I want to open a file-'file.txt'. Inside file.txt 3 files names are there: test1.txt, test2.txt, test3.txt. My work is using file.txt file I have read all 3 files names and copy it to another folder. So for that I have to open file.txt, read the file and print 3 files and only copy these 3 files not full folder and copy these 3 files to another folder'files' which is in same directory.

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

回答by Rajj

try this, here test1 is you source folder, which will contail you files, and test2 is destination folder where you will move your files after reading..

试试这个,这里 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 

or you can try this...

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

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 

yo...

哟...

回答by suhas

if you want to copy entire file as it is then

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

cat filename >> newfilename

for three files

三个文件

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

if you want to copy line by line then

如果你想逐行复制,那么

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

done <"filename"