使用来自文件的值进行令牌替换并创建多个文件,每个文件一对一替换

时间:2017-04-13 14:24:53

标签: bash perl awk sed

我有两个文件:

file1:

 // All valid phone numbers would contain the numeric digits and - sign

for (int pos = 0, len = theValue.length(); pos < len; ++pos) {
    if (! Character.isDigit(theValue.charAt(pos))
            && theValue.charAt(pos) != '-' && theValue.charAt(pos) != '(' && theValue.charAt(pos) != ')' 
            && theValue.charAt(pos) != '+' && theValue.charAt(pos) != ' ' 
            && theValue.charAt(pos) != 'x' && theValue.charAt(pos) != 'X') {
        return false;
    }
}
return true;

file2:

key1
key2
key3

我想创建多个文件:

file_key1:

some useful or useless text
::tok::
some more useful or useless text

file_key2:

some useful or useless text
key1
some more useful or useless text

file_key3:

some useful or useless text
key2
some more useful or useless text

对于sed或awk,我是极端的菜鸟。我可以使用perl脚本或bash脚本执行上述操作。有没有办法用sed或awk来做?

编辑:正如我所要求的用于执行上述任务的perl脚本

some useful or useless text
key3
some more useful or useless text

2 个答案:

答案 0 :(得分:2)

在awk中:

$ awk '
NR==FNR {                  # for the data file
    b=b (NR==1?"":ORS) $0  # buffer the records from the data file
    next                   # next record
}
{
    close(file)            # close previous file
    file="file_" $1        # name current file 
    t=b                    # t is for tmp, b for buffer, baby
    sub(/::tok::/,$1,t)    # replace token with the key
    print t > file         # dump the t to file
}' file2 file1             # mind the order

答案 1 :(得分:0)

试试这个 -

$head f?
==> f1 <==
key1
key2
key3

==> f2 <==
some useful or useless text
::tok::
some more useful or useless text
$cat script.sh
#!/bin/bash
file1=$1
file2=$2
while IFS= read line
do
awk -v line="$line"  '{gsub(/::tok::/,line); print > "fil_"line }'  $file2
done < $file1
$./script.sh f1 f2
$head fil_key?
==> fil_key1 <==
some useful or useless text
key1
some more useful or useless text

==> fil_key2 <==
some useful or useless text
key2
some more useful or useless text

==> fil_key3 <==
some useful or useless text
key3
some more useful or useless text