Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

shell

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

#!/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.

like image 256
user2911160 Avatar asked Oct 23 '13 11:10

user2911160


People also ask

How do I copy a file from one file to another in Unix?

You can use the shell commands cp or pax or the TSO/E command OCOPY to copy files within the z/OS UNIX file system. Using the shell: Use the cp shell command to copy: One file to another file in the working directory, or to a new file in another directory.

How do I copy a file from one file to another in Linux?

You can copy files by right-clicking on the file and selecting "Copy", then going to a different directory and selecting "Paste". For my terminal friends, you can also perform file copy-paste operations without leaving the terminal. In a Linux-based terminal, you do this using the cp command.


2 Answers

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"
like image 140
suhas Avatar answered Oct 20 '22 06:10

suhas


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..

#!/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...

like image 36
Rajj Avatar answered Oct 20 '22 06:10

Rajj