0

I have a bunch of files which need to be translated using custom dictionaries. Each file contains a line indicating which dictionary to use. Here's an example:

*A:
!
=1
*>A_intro
1r
=2
1r
=3
1r
=4
1r
=5
2A:maj
*-

In the file above, *A: indicates to use dictA.

I can translate this part easily using the following syntax:

sed -f dictA < myfile

My problem is that some files require a change of dictionary half way in the text. For example:

*B:
1B:maj
2E:maj/5
2B:maj
2E:maj/5
*C:
2F:maj/5
2C:maj
2F:maj/5
2C:maj
*-

I would like to write a script to automate the translation process. Using this example, I would like the script to read the first line, select dictB, use dictB to translate each line until it reads *C:, select dictC, and then keep going.

  • 2
    I suggest to start with something like this: `while IFS= read -r line; do echo "do something with $line"; done < file` – Cyrus Jan 15 '17 at 14:10

2 Answers2

0

Thanks @Cyrus. That was useful. Here's what I ended up doing.

#!/bin/sh
key="sedDictNull.txt"
while read -r line || [ -n "$line" ]  ## Makes sure that the last line is read. See http://stackoverflow.com/questions/12916352/shell-script-read-missing-last-line
do
        if [[ $line =~ ^\*[Aa]:$ ]]
        then
        key="sedDictA.txt"
        elif [[ $line =~ ^\*[Aa]#:$ ]]
        then
        key="sedDictA#.txt"
        fi
        echo "$line" | sed -f $key 
done < $1
0

I assume your "dictionaries" are really sed scripts that search and replace, like this:

s/2C/nothing/;
s/2B/something/;

You could reorganize these scripts into sections, like this:

/^\*B:/, /^\*[^B]/ {
    s/1B/whatever/;
    s/2B/something/;
}
/^\*C:/, /^\*[^C]/ {
    s/2C/nothing/;
    s/2B/something/;
}

And, of course, you could do that on the fly:

for dict in B C
    do echo "/^\\*$dict:/, /^\\*[^$dict]/ {"
    cat dict.$dict
    echo "}"
done | sed -f- dict.in
Michael Vehrs
  • 3,293
  • 11
  • 10