2017-01-15 42 views
0

我有一堆需要使用自定义字典进行翻译的文件。每个文件都包含一行指示使用哪个字典。这里有一个例子:使用多个字典更改文本文件中的单词

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

在上面的文件,*A:表示使用dictA

我可以很容易地使用下面的语法翻译这一部分:

sed -f dictA < myfile 

我的问题是,一些文件需要的字典一半在文本的变化。例如:

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

我想写一个脚本来自动化翻译过程。使用此示例,我希望脚本读取第一行,选择dictB,使用dictB翻译每行,直到它读取*C:,选择dictC,然后继续。

+2

我建议从这样的事情开始:'while IFS = read -r line;做回声“用$行做某事”;完成 Cyrus

回答

0

谢谢@Cyrus。这很有用。这是我最终做的。

#!/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

我假设你的 “字典” 是真的sed脚本,搜索和替换,就像这样:

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

你可以重新组织这些脚本段,像这样:

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

当然,你可以在飞行中做到这一点:

for dict in B C 
    do echo "/^\\*$dict:/, /^\\*[^$dict]/ {" 
    cat dict.$dict 
    echo "}" 
done | sed -f- dict.in 
相关问题