2013-07-23 62 views
-1

我需要你的幫助在unix.i有一個文件,我有一個值聲明,我必須在調用時替換值。例如我的價值爲& abc和& ccc。現在我必須替換輸出文件中顯示的& abc和& ccc的值。尋找模式並使用unix替換文件中的模式

輸入文件

go to &abc=ddd; if file found &ccc=10; no the value name is &abc; and the age is &ccc;

輸出:

go to &abc=ddd; if file found &ccc=10; now the value name is ddd; and the age is 10;

+0

如果您的問題涉及知道'&abc'可以被替換成'ddd'先驗的,它比如果你要進行詞法分析和解析更簡單似乎是一個特定領域的語言。你能澄清你的問題到底是什麼以及你到底做了什麼? –

回答

1

嘗試使用SED。

#!/bin/bash 

# The input file is a command line argument. 
input_file="${1}" 

# The map of variables to their values 
declare -A value_map=([abc]=ddd [ccc]=10) 

# Loop over the keys in our map. 
for variable in "${!value_map[@]}" ; do 
    echo "Replacing ${variable} with ${value_map[${variable}]} in ${input_file}..." 
    sed -i "s|${variable}|${value_map[${variable}]}|g" "${input_file}" 
done 

這個簡單的bash腳本將用給定文件中的ddd和ccc替換爲10的abc。下面是它的工作在一個簡單的文件的例子:

$ cat file.txt 
so boo aaa abc 
duh 

abc 
ccc 
abcccc 
hmm 
$ ./replace.sh file.txt 
Replacing abc with ddd in file.txt... 
Replacing ccc with 10 in file.txt... 
$ cat file.txt 
so boo aaa ddd 
duh 

ddd 
10 
ddd10 
hmm 
+0

我沒有可變的固定它可以是任何東西。它會是這樣的(&* = sss)。我必須grep它到新的文件,並採取的價值,並取代原來的。 – elangovel

+0

您也可以創建變量及其值參數。這只是一個例子。你是否在同一個文件中搜索你正在進行替換的變量?如果是這樣,那麼它會更棘手,因爲你不想替換變量定義的地方,但你確實想在別處替換它。文件的格式是什麼?一個bash腳本?瞭解語法可能會有所幫助。 – Trenin