1

I'm trying to automatize the creation of an index (the original file has been created with LyX, but it doesn't matter here, I don't want to use the Lyx tool).

For each word I want to index I need to insert, just after each occurence of the word, the following code (with "foo" as example here):

\begin_inset Index idx
status open

\begin_layout Plain Layout
Foo
\end_layout

\end_inset

So, for the moment I use sed:

sed -i 's/foo/foo\n\\begin_inset Index idx\nstatus open\n\n\\begin_layout Plain Layout\nFoo\n\\end_layout\n\n\\end_inset\n\n/g' myfile.lyx

It works, but as I need to index tons of word I'd like to do the same using a file containing a list of all the words I want to index.

For example, I have a file1 containing:

blablabla foo blablabla bar
blaba bar blabla word

And a list file (file2) containing:

foo
bar
word

And I want my file1 as that:

blablabla foo
\begin_inset Index idx
status open

\begin_layout Plain Layout
Foo
\end_layout

\end_inset


blablabla bar
\begin_inset Index idx
status open

\begin_layout Plain Layout
Bar
\end_layout

\end_inset


blaba bar
\begin_inset Index idx
status open

\begin_layout Plain Layout
Bar
\end_layout

\end_inset


blabla word
\begin_inset Index idx
status open

\begin_layout Plain Layout
Word
\end_layout

\end_inset

What is the best way to approach this?

2

If your sed supports -r (or -E) then you can use pattern alternation:

sed -r 's/(foo|bar|word)/\1\n\\begin_inset Index idx\nstatus open\n\n\\begin_layout Plain Layout\n\1\n\\end_layout\n\n\\end_inset\n\n/g'

Basically put the words in the first section as (word1|word2|word3|...) and then you can reference it as \1 in the replace section to put back exactly the word that was matched.

It's then simple enough to build the first pattern from the file. For example,

list=$(tr '\012' '|' < listfile)
list="(${list%?})"
  • It's a good idea, but I have about 300 words to index... That's why using a list file would be better. – Texxet Sep 13 '16 at 19:09
  • Added an example to show how the list expression could be built up – Stephen Harris Sep 13 '16 at 19:24
  • I didn't understand how to build the list with your example. But it inspired me so I did a : cat list | xargs -d '\n' -i sed -ri 's/{}/{}\n\\begin_inset Index idx\nstatus open\n\n\\begin_layout Plain Layout\n\u{}\n\\end_layout\n\n\\end_inset\n\n/g' myfile.lyx – Texxet Sep 14 '16 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.