Sponsored Content
Top Forums Shell Programming and Scripting replace string in file.1 with line from file.2 Post 302315138 by ccox85 on Monday 11th of May 2009 03:56:27 PM
Old 05-11-2009
replace string in file.1 with line from file.2

Hello all, the title makes this sound simple, and maybe it should be.

This is by code:
Code:
#!/bin/sh
cp ch25.txt ch25.fn.tex
n=`grep -c '^\[' ch25_footnotes.txt`

for i in {1..$n}
do
        `grep '^\[$i\]' ch25_footnotes.txt > temp`
        r=`awk -F] '{print $2}' temp`
        `sed 's/\[$i\]/\\footnote{$r}/' ch25.fn.tex`
done

This is what I am trying to do. I have a file like this:
Quote:
First there was nothing. Then there was Calvin[1].
That contains a body of text with footnotes markers, that are of exactly that format [i]. Square brackets are not used otherwise in the text... at least no patters of the form [integer] exist except for footnote markers.

I have a another file of the footnote text, like this
Quote:
[1] A memorable quote from Bill Waterson's Calvin and Hobbes.
What that code I wrote is attempting to do is:
  1. Create a copy of the body text to mess with.
  2. Count the number of footnotes that exist.
  3. Initiate a For loop that will generate an $i for every integer up to $n, the number of footnotes.
  4. grep the line starting with [$i] and save stick it into a temp file.
  5. use awk to grab only the text portion of the footnote (skipping the [$i] number at the beginning of the line) and store that in variable r.
  6. Finally, search the main file for the [$i] marker and add the footnote, alone with \footnote{} markup for latex.
  7. Repeat hundreds of times (-;

I am not all that great with scripting, but this is my thought process and what I have tried. Right now... nothing happens. I execute the script, and it just hangs, and I have to break the script.

In case you are wondering, I am just trying to typeset Marx's Das Kapital for posterity and easier reading. I do not plan on printing or distributing... just taking a freely available reading material and making it pretty.

Thank you!

Last edited by ccox85; 05-11-2009 at 05:28 PM..
 

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

how can search a String in one text file and replace the whole line in another file

i am very new to UNIX plz help me in this scenario i have two text files as below file1.txt name=Rajakumar. Discipline=Electronics and communication. Designation=software Engineer. file2.txt name=Kannan. Discipline=Mechanical. Designation=CADD Design Engineer. ... (6 Replies)
Discussion started by: kkraja
6 Replies

2. Shell Programming and Scripting

Replace string in a file within a range of line

Hi, I want to replace the srting '; with ABCD'; in a file from line 1 to line 65. Is there any single command to do it without using awk Thanks for quick reply https://www.unix.com/images/misc/progress.gif (3 Replies)
Discussion started by: tosattam
3 Replies

3. Shell Programming and Scripting

To trim Certain field in a line of a file and replace the new string in that position

To trim 3rd field in for all the lines of a file and replace the modified string in that particular field. For example i have a file called Temp.txt having content Temp.txt ----------------- 100,234,M1234 400,234,K1734 300,345,T3456 ---------------- So the modified file output should... (4 Replies)
Discussion started by: rpadhi
4 Replies

4. Shell Programming and Scripting

replace (sed?) a single line/string in file with multiple lines (string) from another file??

Can someone tell me how I can do this? e.g: Say file1.txt contains: today is monday the 22 of NOVEMBER 2010 and file2.txt contains: the 11th month of How do i replace the word NOVEMBER with (5 Replies)
Discussion started by: tuathan
5 Replies

5. Shell Programming and Scripting

Replace line in file with line in another file based on matching string

Hi I am not the best scripter in the world and have run into a issue which you might be able to guide me on... I have two files. File1 : A123, valueA, valueB B234, valueA, valueB C345, valueA, valueB D456, valueA, valueB E567, valueA, valueB F678, valueA, valueB File2: C345,... (5 Replies)
Discussion started by: luckycharm
5 Replies

6. Shell Programming and Scripting

sed or awk to replace a value in a certain line from another file containing a string

Hi experts, In my text file I have the following alot of lines like below. input.k is as follows. 2684717 -194.7050476 64.2345581 150.6500092 0 0 2684718 -213.1575623 62.7032242 150.6500092 0 0 *INCLUDE $# filename... (3 Replies)
Discussion started by: hamnsan
3 Replies

7. Shell Programming and Scripting

Replace and add line in file with line in another file based on matching string

Hi, I want to achieve something similar to what described in another post: The difference is I want to add the line if the pattern is not found. File 1: A123, valueA, valueB B234, valueA, valueB C345, valueA, valueB D456, valueA, valueB E567, valueA, valueB F678, valueA, valueB ... (11 Replies)
Discussion started by: jyu3
11 Replies

8. Shell Programming and Scripting

Replace a string with each line from another file repeatedly

I don't know if it's been asked before but seems i gave up seeking. i have 2 files : file1.txt Monday XXXX Tuesday XXXX XXXX Wednesday Thursday XXXX XXXX is in every lines of file1.txt and i want to replace them with each line in file2.txt: home school cinema so output file is: ... (19 Replies)
Discussion started by: perseous
19 Replies

9. Shell Programming and Scripting

Replace line in file with line in another file based on matching string

HI Can any one guide me how to achieve this task. I have 2 files env.txt #Configuration.Properties values identity_server_url = http://identity.test-hit.com:9783/identity/service/user/register randon_password_length = 6 attachment_file_path = /pass/temp/attachments/... (1 Reply)
Discussion started by: nikilbr86
1 Replies

10. UNIX for Dummies Questions & Answers

Search for a string,delete the line and replace with new string in a file

Hi Everyone, I have a requirement in ksh where i have a set of files in a directory. I need to search each and every file if a particular string is present in the file, delete that line and replace that line with another string expression in the same file. I am very new to unix. Kindly help... (10 Replies)
Discussion started by: Pradhikshan
10 Replies
expander(n)					      Text expansion and template processing					       expander(n)

NAME
expander - Procedures to process templates and expand text. SYNOPSIS
package require Tcl 8.2 package require textutil::expander ?1.0.1? ::textutil::expander expanderName expanderName cappend text expanderName cget varname expanderName cis cname expanderName cname expanderName cpop cname expanderName cpush cname expanderName cset varname value expanderName cvar varname expanderName errmode newErrmode expanderName evalcmd ?newEvalCmd? expanderName expand string ?brackets? expanderName lb ?newbracket? expanderName rb ?newbracket? expanderName reset expanderName setbrackets lbrack rbrack expanderName textcmd ?newTextCmd? DESCRIPTION
The Tcl subst command is often used to support a kind of template processing. Given a string with embedded variables or function calls, subst will interpolate the variable and function values, returning the new string: % set greeting "Howdy" Howdy % proc place {} {return "World"} % subst {$greeting, [place]!} Howdy, World! % By defining a suitable set of Tcl commands, subst can be used to implement a markup language similar to HTML. The subst command is efficient, but it has three drawbacks for this kind of template processing: o There's no way to identify and process the plain text between two embedded Tcl commands; that makes it difficult to handle plain text in a context-sensitive way. o Embedded commands are necessarily bracketed by [ and ]; it's convenient to be able to choose different brackets in special cases. Someone producing web pages that include a large quantity of Tcl code examples might easily prefer to use << and >> as the embedded code delimiters instead. o There's no easy way to handle incremental input, as one might wish to do when reading data from a socket. At present, expander solves the first two problems; eventually it will solve the third problem as well. The following section describes the command API to the expander; this is followed by tutorial section. EXPANDER API
The textutil::expander package provides only one command, described below. The rest of the section is taken by a description of the methods for the exapnder objects created by this command. ::textutil::expander expanderName The command creates a new expander object with an associated Tcl command whose name is expanderName. This command may be used to invoke various operations on the graph. If the expanderName is not fully qualified it is interpreted as relative to the current namespace. The command has the following general form: expanderName option ?arg arg ...? Option and the args determine the exact behavior of the command. The following commands are possible for expander objects: expanderName cappend text Appends a string to the output in the current context. This command should rarely be used by macros or application code. expanderName cget varname Retrieves the value of variable varname, defined in the current context. expanderName cis cname Determines whether or not the name of the current context is cname. expanderName cname Returns the name of the current context. expanderName cpop cname Pops a context from the context stack, returning all accumulated output in that context. The context must be named cname, or an error results. expanderName cpush cname Pushes a context named cname onto the context stack. The context must be popped by cpop before expansion ends or an error results. expanderName cset varname value Sets variable varname to value in the current context. expanderName cvar varname Retrieves the internal variable name of context variable varname; this allows the variable to be passed to commands like lappend. expanderName errmode newErrmode Sets the macro expansion error mode to one of nothing, macro, error, or fail; the default value is fail. The value determines what the expander does if an error is detected during expansion of a macro. o If the error mode is fail, the error propagates normally and can be caught or ignored by the application. o If the error mode is error, the macro expands into a detailed error message, and expansion continues. o If the error mode is macro, the macro expands to itself; that is, it is passed along to the output unchanged. o If the error mode is nothing, the macro expands to the empty string, and is effectively ignored. expanderName evalcmd ?newEvalCmd? Returns the current evaluation command, which defaults to uplevel #0. If specified, newEvalCmd will be saved for future use and then returned; it must be a Tcl command expecting one additional argument: the macro to evaluate. expanderName expand string ?brackets? Expands the input string, replacing embedded macros with their expanded values, and returns the expanded string. If brackets is given, it must be a list of two strings; the items will be used as the left and right macro expansion bracket sequences for this expansion only. expanderName lb ?newbracket? Returns the current value of the right macro expansion bracket; this is for use as or within a macro, when the bracket needs to be included in the output text. If newbracket is specified, it becomes the new bracket, and is returned. expanderName rb ?newbracket? Returns the current value of the right macro expansion bracket; this is for use as or within a macro, when the bracket needs to be included in the output text. If newbracket is specified, it becomes the new bracket, and is returned. expanderName reset Resets all expander settings to their initial values. Unusual results are likely if this command is called from within a call to expand. expanderName setbrackets lbrack rbrack Sets the left and right macro expansion brackets. This command is for use as or within a macro, or to permanently change the bracket definitions. By default, the brackets are [ and ], but any non-empty string can be used; for example, < and > or (* and *) or even Hello, and World!. expanderName textcmd ?newTextCmd? Returns the current command for processing polain text, which defaults to the empty string, meaning identity. If specified, new- TextCmd will be saved for future use and then returned; it must be a Tcl command expecting one additional argument: the text to process. The expander object will this command for all plain text it encounters, giving the user of the object the ability to process all plain text in some standard way before writing it to the output. The object expects that the command returns the pro- cessed plain text. Note that the combination of "textcmd plaintext" is run through the evalcmd for the actual evaluation. In other words, the textcmd is treated as a special macro implicitly surrounding all plain text in the template. TUTORIAL
To begin, create an expander object: % package require expander 1.0 % ::expander::expander myexp ::myexp % The created ::myexp object can be used to expand text strings containing embedded Tcl commands. By default, embedded commands are delim- ited by square brackets. Note that expander doesn't attempt to interpolate variables, since variables can be referenced by embedded com- mands: % set greeting "Howdy" Howdy % proc place {} {return "World"} % ::myexp expand {[set greeting], [place]!} Howdy, World! % Embedding Macros An expander macro is simply a Tcl script embedded within a text string. Expander evaluates the script in the global context, and replaces it with its result string. For example, % set greetings {Howdy Hi "What's up"} Howdy Hi "What's up" % ::myexp expand {There are many ways to say "Hello, World!": [set result {} foreach greeting $greetings { append result "$greeting, World! " } set result] And that's just a small sample!} There are many ways to say "Hello, World!": Howdy, World! Hi, World! What's up, World! And that's just a small sample! % Writing Macro Commands More typically, macro commands are used to create a markup language. A macro command is just a Tcl command that returns an output string. For example, expand can be used to implement a generic document markup language that can be retargeted to HTML or any other output format: % proc bold {} {return "<b>"} % proc /bold {} {return "</b>"} % ::myexp expand {Some of this text is in [bold]boldface[/bold]} Some of this text is in <b>boldface</b> % The above definitions of bold and /bold returns HTML, but such commands can be as complicated as needed; they could, for example, decide what to return based on the desired output format. Changing the Expansion Brackets By default, embedded macros are enclosed in square brackets, [ and ]. If square brackets need to be included in the output, the input can contain the lb and rb commands. Alternatively, or if square brackets are objectionable for some other reason, the macro expansion brackets can be changed to any pair of non-empty strings. The setbrackets command changes the brackets permanently. For example, you can write pseudo-html by change them to < and >: % ::myexp setbrackets < > % ::myexp expand {<bold>This is boldface</bold>} <b>This is boldface</b> Alternatively, you can change the expansion brackets temporarily by passing the desired brackets to the expand command: % ::myexp setbrackets "[" "]" % ::myexp expand {<bold>This is boldface</bold>} {< >} <b>This is boldface</b> % Customized Macro Expansion By default, macros are evaluated using the Tcl uplevel #0 command, so that the embedded code executes in the global context. The applica- tion can provide a different evaluation command using evalcmd; this allows the application to use a safe interpreter, for example, or even to evaluated something other than Tcl code. There is one caveat: to be recognized as valid, a macro must return 1 when passed to Tcl's "info complete" command. For example, the following code "evaluates" each macro by returning the macro text itself. proc identity {macro} {return $macro} ::myexp evalcmd identity Using the Context Stack Often it's desirable to define a pair of macros which operate in some way on the plain text between them. Consider a set of macros for adding footnotes to a web page: one could have implement something like this: Dr. Pangloss, however, thinks that this is the best of all possible worlds.[footnote "See Candide, by Voltaire"] The footnote macro would, presumably, assign a number to this footnote and save the text to be formatted later on. However, this solution is ugly if the footnote text is long or should contain additional markup. Consider the following instead: Dr. Pangloss, however, thinks that this is the best of all possible worlds.[footnote]See [bookTitle "Candide"], by [authorsName "Voltaire"], for more information.[/footnote] Here the footnote text is contained between footnote and /footnote macros, continues onto a second line, and contains several macros of its own. This is both clearer and more flexible; however, with the features presented so far there's no easy way to do it. That's the purpose of the context stack. All macro expansion takes place in a particular context. Here, the footnote macro pushes a new context onto the context stack. Then, all expanded text gets placed in that new context. /footnote retrieves it by popping the context. Here's a skeleton implementation of these two macros: proc footnote {} { ::myexp cpush footnote } proc /footnote {} { set footnoteText [::myexp cpop footnote] # Save the footnote text, and return an appropriate footnote # number and link. } The cpush command pushes a new context onto the stack; the argument is the context's name. It can be any string, but would typically be the name of the macro itself. Then, cpop verifies that the current context has the expected name, pops it off of the stack, and returns the accumulated text. Expand provides several other tools related to the context stack. Suppose the first macro in a context pair takes arguments or computes values which the second macro in the pair needs. After calling cpush, the first macro can define one or more context variables; the second macro can retrieve their values any time before calling cpop. For example, suppose the document must specify the footnote number explic- itly: proc footnote {footnoteNumber} { ::myexp cpush footnote ::myexp csave num $footnoteNumber # Return an appropriate link } proc /footnote {} { set footnoteNumber [::myexp cget num] set footnoteText [::myexp cpop footnote] # Save the footnote text and its footnoteNumber for future # output. } At times, it might be desirable to define macros that are valid only within a particular context pair; such macros should verify that they are only called within the correct context using either cis or cname. HISTORY
expander was written by William H. Duquette; it is a repackaging of the central algorithm of the expand macro processing tool. SEE ALSO
regexp, split, string, http://www.wjduquette.com/expand KEYWORDS
string, template processing, text expansion textutil 1.0.1 expander(n)
All times are GMT -4. The time now is 02:12 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy