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.
Let's say I have a file with the following content:
I need a shell script that can produce the following file:
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.
TheScript is in biterscripting ( http://www.biterscripting.com
). To try, save the script as /Scripts/lines.txt, start biterscripting and enter the following command.
Script can also be called directly from another program, or another shell, as,
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.