2014-04-30 172 views
0

我正在開發一個bash腳本來備份MySQL。我需要從文件中讀取一系列字符串,並將它們傳遞給腳本中的變量。例如:從文件讀入變量 - Bash腳本

像這樣的事情會在文件中(file.txt的)

database1 table1 
database1 table4 
database2 
database3 table2 

我的腳本需要讀取該文件,並把這些字符串變量,如:

#! bin/bash 
LIST="database1.table1|database1.table4|database2|database3.table2" 

編輯。我改變主意了,現在我需要這樣的輸出:

database1.table1.*|database1.table4.*|database2*.*|database3.table2.* 
+2

你到目前爲止嘗試過什麼? –

+1

你也需要修復shebang,它會是'#!/ bin/bash' – devnull

回答

6

你可以使用tr更換新行和空格:

LIST=$(tr ' \n' '.|' < file.txt) 

由於輸入文件的最後一行可能包含一個新行本身,你需要擺脫它:

LIST=$(tr ' ' '.' < file.txt | paste -sd'|') 
5

用awk:

s=$(awk '{$1=$1}1' OFS='.' ORS='|' file) 
LIST="${s%|}" 

echo "$LIST" 
database1.table1|database1.table4|database2|database3.table2 
+0

這真是太棒了!我忘了提一件事。我還需要在輸出字符串中添加一些通配符。條件是:如果我們讀取database2,輸出應該是database2 *。*,如果我們讀取一個數據庫和一個表,輸出應該是database1.table1。*我要查找的最終結果是:database1.table1。* | database1.table4。* | database2 *。* | database3.table2。* 請幫忙:) – andresg3

+0

這實際上改變了問題的本質。如果你打開一個新的問題鏈接到這個問題,我將嘗試解決它。 – anubhava

+0

http://stackoverflow.com/questions/23412765/read-from-file-into-variable-bash-script-take2 – andresg3

2

如果數據中沒有出現,您可以用需要使用sed的字符替換新行。

例如

FOO=$(sed '{:q;N;y/ /./;s/\n/|/g;t q}' /home/user/file.txt) 
+0

我怎麼能得到這個輸出,而不是'database1.table1。* | database1.table4。* | database2 *。* | database3.table2。*' - 請注意'。*'和'*。*' - 換句話說:如果只有沒有表的數據庫,我需要在末尾添加'*。*',並且當有一個database.table時,我需要添加'。*' – andresg3

3

的bash(版本4相信)

mapfile -t lines < file.txt   # read lines of the file into an array 
lines=("${lines[@]// /.}")   # replace all spaces with dots 
str=$(IFS='|'; echo "${lines[*]}") # join the array with pipe 
echo "$str" 
database1.table1|database1.table4|database2|database3.table2 

mapfile -t lines < file.txt 
for ((i=0; i<${#lines[@]}; i++)); do 
    [[ ${lines[i]} == *" "* ]] && lines[i]+=" *" || lines[i]+="* *" 
done 
str=$(IFS='|'; echo "${lines[*]// /.}") 
echo "$str" 
database1.table1.*|database1.table4.*|database2*.*|database3.table2.* 
+1

您不需要輔助變量,因爲目的是隻打印到stdout。在一個子shell中(IFS ='|'; echo「$ {lines [*]}」)'就足夠了。實際上,你甚至不需要輔助線:'mapfile -t lines

+0

我怎樣才能得到這個輸出,而不是'database1.table1。* | database1.table4。* | database2 *。* | database3.table2。*' - 請注意'。*'vs'*。*' - 換句話說:如果只有沒有表的數據庫,我需要在末尾添加'*。*',並且在那裏是一個database.table我需要添加'。*' – andresg3

+0

@ andresg3,done –