1

次のような bash の変数にテキスト文字列があります。

filename1.txt
filename2.txt

varname1 = v1value
$(varname1)/filename3.txt
$(varname1)/filename4.txt

varname2 = $(varname1)/v2value
$(varname2)/filename5.txt
$(varname2)/filename6.txt

すべての変数を適切な場所に置き換えて、次のようにします。

filename1.txt
filename2.txt

v1value/filename3.txt
v1value/filename4.txt

v1value/v2value/filename5.txt
v1value/v2value/filename6.txt

シェルでこれを行うためのクリーンな方法を提案できる人はいますか?

4

3 に答える 3

2

awk で:

BEGIN {
    FS = "[[:space:]]*=[[:space:]]*"
}

NF > 1 {
    map[$1] = $2
    next;
}

function replace(     count)
{
    for (key in map) {
        count += gsub("\\$\\("key"\\)", map[key])
    }

    return count
}

{
    while (replace() > 0) {}
    print
}

ルアで:

local map = {}

--for line in io.lines("file.in") do -- To read from a file.
for line in io.stdin:lines() do -- To read from standard input.
    local key, value = line:match("^(%w*)%s*=%s*(.*)$")
    if key then
        map[key] = value
    else
        local count
        while count ~= 0 do
            line, count = line:gsub("%$%(([^)]*)%)", map)
        end
        print(line)
    end
end
于 2014-09-05T02:00:43.147 に答える
1

を使用して合理的な解決策を見つけましたm4

function make_substitutions() {
    # first all $(varname)s are replaced with ____varname____
    # then each assignment statement is replaced with an m4 define macro
    # finally this text is then passed through m4

    echo "$1" |\
    sed 's/\$(\([[:alnum:]][[:alnum:]]*\))/____\1____/' | \
    sed 's/ *\([[:alnum:]][[:alnum:]]*\) *= *\(..*\)/define(____\1____, \2)/' | \
    m4
}
于 2014-09-04T21:31:27.293 に答える
0

多分

echo "$string" | perl -nlE 'm/(\w+)\s*=\s*(.*)(?{$h{$1}=$2})/&&next;while(m/\$\((\w+)\)/){$x=$1;s/\$\($x\)/$h{$x}/e};say$_'

版画

filename1.txt
filename2.txt

v1value/filename3.txt
v1value/filename4.txt

v1value/v2value/filename5.txt
v1value/v2value/filename6.txt
于 2014-09-04T23:46:51.710 に答える