Shell Script - Copy text from one file to another

Linux is a very robust operating system, requiring much practice and knowledge. However, as one starts using Linux on a regular basis, handling files, copying, using shell script all becomes quite effortless and straightforward. If you are having problems copying text from a file to another when using shell script, then have a read of the article below. Even someone new to /faq/linux-97Linux operating system, should be able to execute the task by following the instructions below.


I need to copy text between a start and an end pattern from one file to another.
For example,

Let's say I have a file with the following content:

hello world1   
hello world2   
hello world3   
hello world4   
hello world5   

I need a shell script that can produce the following file:

hello world2   
hello world3   
hello world4   
hello world5   

I do not know the line numbers for the range I want to copy, I just want to copy from the occurrence of 'hello world2' to the occurrence of 'hello world5'+1 line

In case you are wondering what I am trying to do here, I want to run a thread dump on my machine using kill -3 <pid> but the output of this goes to standard output which in my case is directed to the jboss out file which has a lot of other logs in it. So I want to run this script to extract the thread dumps into a separate file once the kill has been executed. Needless to say, there might be more than one thread dump in the jboss.out file.


The simplest way, if your input file is at /folder/somefile.txt,

# Script lines.txt   
# Read input file into a string variable.   
var str input ; cat "/folder/somefile.txt" > $input   
# Remove everything before "hello world2".   
stex "]^hello world2^" $input > null   
# Remove everything after "hello world5n".   
stex "^hello world5n^[" $input > null   
# $input now has only the desired portion. Print it.   
echo $input 

TheScript is in biterscripting ( ). To try, save the script as /Scripts/lines.txt, start biterscripting and enter the following command.

script lines.txt

Script can also be called directly from another program, or another shell, as,

/biterScripting/biterScripting.exe lines.txt

Make sure you use the correct file location instead of /folder/somefile.txt. Note the double quotes, ^, [ and ] in the string extractor command syntax. Feel free to translate the script to any other language.


Thanks to SenHu for this tip on the forum.
Published by aakai1056. Latest update on March 2, 2012 at 05:27 PM by Virginia Parsons.
This document, titled "Shell Script - Copy text from one file to another," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (
OCS error - Invalid command 'PerlSetEnv'
Linux - GRUB error 22, Cannot run Live CD