字符串替换从文本文件到另一个字符串

时间:2014-04-16 17:30:25

标签: sql string bash awk sed

我有一个文本文件,每行有三列文本(字符串)。我想通过将三个字符串中的每一个替换为骨架SQL命令来创建SQL插入命令。我已经在骨架脚本中放置了标记并使用了SED s / placemarker1 / first string /但没有成功。有没有更简单的方法来完成这项任务。我使用管道重复“第二个字符串”等过程。我实际上使用awk来获取字段但无法转换为实际值。

enter code here
    for i in [ *x100* ]; do
    if [ -f "$i" ]; then {
        grep -e "You received a payment" -e "Transaction ID:" -e "Receipt No: " $i  >> ../temp
        cat ../temp | awk 'NR == 1 {printf("%s\t",$9)} NR == 2 {printf("%s\t",$9)}  NR == 3 {printf("%s\n",$3)}' | awk '{print $2,$1,$3}' | sed 's/(/ /' | sed 's/)./ /' >> ../temp1
        cat temp1 | awk 'email="$1"; transaction="$2"; ccreceipt="$3";'
        cat /home/linux014/opt/skeleton.sql | sed 's/EMAIL/"$email"/' | sed 's/TRANSACTION/"$transaction"/' | sed 's/CCRECEIPT/"$ccreceipt"/' > /home/linux014/opt/new-member.sql
        rm -f ../temp
    } fi
    done

我无法弄清楚如何获取值而不是插入到我的字符串中的变量的名称。

示例输入(仅限一行):

catdog@gmail.com 2w4e5r6t7y8u9i8u7 1111-2222-3333-4444

示例实际输出:

INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('"$email"','"$transaction"','"$ccreceipt"');

首选输出:

INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('catdog@gmail.com','2w4e5r6t7y8u9i8u7','1111-2222-3333-4444');

3 个答案:

答案 0 :(得分:2)

awk '{print "INSERT INTO users (email,paypal_tran,CCReceipt) VALUES"; print "(\x27"$1"\x27,\x27"$2"\x27,\x27"$3"\x27);"}' input.txt

将您的样本输入转换为首选输出。它应该适用于多行输入。

修改

您在此行中使用的变量:

cat temp1 | awk 'email="$1"; transaction="$2"; ccreceipt="$3";'

仅对awk和此命令可见。它们不是shell变量。 同样在您的sed命令中删除那些单引号,然后您可以获取值:

sed "s/EMAIL/$email/"

答案 1 :(得分:1)

您可以尝试此bash

while read email transaction ccreceipt; do echo "INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('$email','$transaction','$ccreceipt');"; done<inputfile

inputfile中:

catdog@gmail.com 2w4e5r6t7y8u9i8u7 1111-2222-3333-4444
dog@gmail.com 2dsdsda53563u9i8u7 3333-4444-5555-6666

<强>测试

sat:~$ while read email transaction ccreceipt; do echo "INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('$email','$transaction','$ccreceipt')"; done<inputfile
INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('catdog@gmail.com','2w4e5r6t7y8u9i8u7','1111-2222-3333-4444')
INSERT INTO users (email,paypal_tran,CCReceipt) VALUES ('dog@gmail.com','2dsdsda53563u9i8u7','3333-4444-5555-6666')

答案 2 :(得分:0)

You can write a small procedure for this

CREATE PROCEDURE [dbo].[appInsert]--
@string VARCHAR(500)
AS
BEGIN

DECLARE @I INT  
DECLARE @SubString VARCHAR(500)
SET @String = 'catdog@gmail.com 2w4e5r6t7y8u9i8u7 1111-2222-3333-4444'
SET @I = 1  
SET @String = REPLACE(@String, ' ', '`~`')

    WHILE @I > 0
        BEGIN
        SET @SubString = SUBSTRING (REVERSE(@String), 1, ( CHARINDEX( '`~`', REVERSE(@String)) - 1))
        SET @String = SUBSTRING(@String, 1, LEN(@String) - CHARINDEX( '`~`', REVERSE(@String)) - 2 )
        print REVERSE(@SubString) + ' === ' + @String
        SET @i = CHARINDEX( '`~`', @String)
        END

END