Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Dummies Questions & Answers


UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !!

Closed Thread    
 
Thread Tools Search this Thread Display Modes
    #1  
Old 06-25-2012
Registered User
 
Join Date: Oct 2005
Posts: 70
Thanks: 0
Thanked 1 Time in 1 Post
Append Files

Hi All,

I have to append 2 lines at the end of a text file. If those 2 lines are already there then do not append else append the 2 lines to the text file.

Eg: I have a text file, file.txt

This text file might look like this,

/home/kp/make.jsp
/home/pk/model.jsp

I have to append these 2 lines /home/kk/file1.txt and /home/kk1/file2.txt at the end of file.txt.

Appended file looks like this,

file.txt:

/home/kp/make.jsp
/home/pk/model.jsp
home/kk/file1.txt
/home/kk1/file2.txt

The script has to check if file.txt has those lines /home/kk/file1.txt and /home/kk1/file2.txt before appending them at the end of the text file file.txt.

if the 2 lines already there in file.txt then the script should not append the 2 lines.

can someone please tell me how can I do this using korn shell.

Thanks
pavan
Sponsored Links
    #2  
Old 06-25-2012
Registered User
 
Join Date: Sep 2008
Location: US
Posts: 152
Thanks: 14
Thanked 14 Times in 13 Posts
One can use tail and head to get the last two lines from a file:


Code:
 
one_before_last=$( tail -2 my_input|head -1 )
the_last_line=$(tail -1 my_input)

To determine if the line is present one can use grep -q - it will return 1 if not found, which can be used with
Code:
||

construct

To put it together one can do something like this:


Code:
 
#!/bin/ksh
input_file_1="your-name-here"
input_file_2="yeor-name-here"
my_output_file="your-name-here"
F1N1=$(tail -2 $input_file_1|head -1)
F1N2=$(tail -1 $input_file_1)
F2N1=$(tail -2 $input_file_2|head -1)
F2N2=$(tail -1 $input_file_2)
grep -q "$F1N1" $my_output_file || echo "$F1N1" >> $my_output_file
grep -q "$F1N2" $my_output_file || echo "$F1N2" >> $my_output_file
grep -q "$F2N1" $my_output_file || echo "$F2N1" >> $my_output_file
grep -q "$F2N2" $my_output_file || echo "$F2N2" >> $my_output_file

Hope this will give you an idea.
Sponsored Links
Closed Thread

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
append to two files Sara_84 Shell Programming and Scripting 3 02-19-2012 03:26 AM
Append all files in a folder pandeyak Shell Programming and Scripting 7 06-30-2010 05:34 PM
MV all files and append date markdjones82 Shell Programming and Scripting 2 01-19-2010 05:37 PM
append two files princessotes UNIX for Dummies Questions & Answers 1 05-01-2009 11:26 AM
Match & append the files shashi_kiran_v UNIX for Dummies Questions & Answers 2 12-14-2005 06:21 AM



All times are GMT -4. The time now is 06:39 AM.