2017-12-03 327 views
0

我正在編寫shell腳本來替換數據庫中的名稱,爲此,我有用戶列表中的當前名稱和新名稱在.txt文件中。文件格式是像下面需要shell腳本語法幫助「for循環和awk」

**new name  current name** 
abc    pqr 
def    stq 
mnd    tdh 

對於這個我寫個「for循環」使用awk命令,在這裏我想它應該給我的$1abc值,defmnd

我寫下如下循環,

function() 
{ 
cd $directory 

for i `cat $filename.txt` | awk '{print $1}' 
do 
     j=`grep "$i `cat $filename.txt ` | awk '{print $1'} |awk '{print $2}'"` 
     echo "update table SET username = '$i' WHERE username = '$j;" 
done 
} 

但不知何故,這是行不通的。有人可以幫助在這裏寫代碼在shell腳本?

回答

0

你不提一個數據庫或您的環境,但我認爲你只是想是這樣的:

awk '{print "update table SET username=" $1 " where username=" $2 ";"}' filename.txt| someSQLshell 

樣本輸出

update table SET username=newboy where username=oldboy; 
update table SET username=newemployee where username=badboy; 

測試輸入

newboy oldboy 567 q 
newemployee badboy 190 r 

我不知道mysql,但我相信你能管到的命令,所以:

awk '{print "update table SET username=" $1 " where username=" $2 ";"}' filename.txt | mysql -h HOST -u USER -p PASSWORD DBNAME 

這可能工作過,但效率不高:

awk '{print "mysql -u user -p pass -e \"update table set username=" $1 " where username=" $2 "\""}' filename.txt 

樣品輸出

mysql -u user -p pass -e "update table set username=newboy where username=oldboy" 
mysql -u user -p pass -e "update table set username=newemployee where username=badboy" 

如果這看起來是正確的,您可以將其管bash

awk '{...}' | bash 

如果你真的想用bashfor循環,你可以做這樣的事情:

#!/bin/bash 
cat filename.txt | while read new old _ ; do 
    echo "update table SET username=$new where username=$old;" 
done | mysql -u USER -p PASSWORD DBNAME 

在末尾留下| mysql ...位以查看準備好的輸出mysql

+0

我在我們的環境中使用mysql .. – user263076

+0

我有一個'mysql'嘗試一下,但謹慎行事,並用非常短的文件進行測試,以防萬一它出錯。 –

+0

很酷..謝謝..它工作。 – user263076