使用awk/sed查找并替换文件到其他文件的键值对
我有一个键值文件,名为使用awk/sed查找并替换文件到其他文件的键值对,awk,sed,Awk,Sed,我有一个键值文件,名为key.txt,带有:分隔符。 以下是显示值的方式: server_name:server1 username:someuser keyname:123key 我的第二个文件是一个脚本文件,它在整个文件中都有这些键。它以以下格式显示在文件中的任何位置,无论是哪一行或哪一列: what is the servername '%%server_name%%' Enter your username '%%username%%' What is the ssh key val
key.txt
,带有:
分隔符。
以下是显示值的方式:
server_name:server1
username:someuser
keyname:123key
我的第二个文件是一个脚本文件,它在整个文件中都有这些键。它以以下格式显示在文件中的任何位置,无论是哪一行或哪一列:
what is the servername '%%server_name%%'
Enter your username '%%username%%'
What is the ssh key value '%%keyname%%'
我要做的是,当我运行命令时,它将在我的第二个文件中找到键服务器名称
,并将键%%server\u名称%
替换为文件1中的值,该文件是server1
,但确保它在前后都有引号
因此,我的新文件将如下所示:
what is the servername 'server1'
Enter your username 'someuser'
What is the ssh key value '123key'
我在论坛上找到了这个代码,但无法使它工作
awk 'NR==FNR {url[$1]=$2; next} {for (i=1; i<=NF; i++) if ($i in url) $i=url[$i]; print}' key.txt file2.txt
+ xxd keys.txt
0000000: 7371 6c5f 7365 7276 6572 5f6e 616d 653a sql_server_name:
0000010: 7465 7374 5f73 6571 7365 7276 6572 5f31 test_seqserver_1
0000020: 3233 340d 0a0d 0a73 716c 5f6c 6f67 696e 234....sql_login
0000030: 5f6e 616d 653a 7465 7374 5f6c 6f67 696e _name:test_login
0000040: 5f6e 616d 650d 0a0d 0a70 6173 7377 6f72 _name....passwor
0000050: 643a 7465 7374 5f70 6173 7377 6f72 6420 d:test_password
0000060: 0d0a 0d0a 5349 443a 3132 3334 3536 200d ....SID:123456 .
0000070: 0a0d 0a64 6566 6175 6c74 5f64 6174 6162 ...default_datab
0000080: 6173 653a 7465 6d70 6462 0d0a 0d0a 6465 ase:tempdb....de
0000090: 6661 756c 745f 6c61 6e67 7561 6765 3a75 fault_language:u
00000a0: 735f 656e 676c 6973 680d 0a0d 0a63 6865 s_english....che
00000b0: 636b 5f65 7870 6972 6174 696f 6e3a 4f46 ck_expiration:OF
00000c0: 460d 0a0d 0a63 6865 636b 5f70 6f6c 6963 F....check_polic
00000d0: 793a 4f46 460d 0a0d 0a64 656c 6976 6572 y:OFF....deliver
00000e0: 7974 7970 653a 7363 6865 6475 6c65 640d ytype:scheduled.
00000f0: 0a0d 0a73 6368 6564 756c 6564 5f64 656c ...scheduled_del
0000100: 6976 6572 7964 6174 653a 3035 2d33 302d iverydate:05-30-
0000110: 3230 3939 0d0a 0d0a 7363 6865 6475 6c65 2099....schedule
0000120: 645f 6465 6c69 7665 7279 5f32 3468 725f d_delivery_24hr_
0000130: 6365 6e74 7261 6c5f 7469 6d65 3a31 3135 central_time:115
0000140: 3920 0d0a 0d0a 0d0a 0d0a 0d0a 0d0a 0d0a 9 ..............
awk'NR==FNR{url[$1]=$2;next}{for(i=1;i您可以使用sed将key.txt
转换为一系列sed替换,然后在输入文件上运行这些替换:
$ sed '/^[[:blank:]]*$/d;s|^|s/%%|;s|:|%%/|;s|$|/|' key.txt | sed -f - infile
what is the servername 'server1'
Enter your username 'someuser'
What is the ssh key value '123key'
第一个sed命令具有以下输出:
s/%%server_name%%/server1/
s/%%username%%/someuser/
s/%%keyname%%/123key/
然后我们使用sed-f-
运行这些命令,其中-f
表示“从文件读取命令”,而特殊文件-
是标准输入
进一步了解第一个命令的作用:
sed '
/^[[:blank:]]*$/d # Delete blank lines in key file
s|^|s/%%| # Insert "s/%%" at the start of the line
s|:|%%/| # Replace ":" with "%%/"
s|$|/| # Insert "/" at the end of the line
' key.txt
我使用|
作为分隔符,而不是更常见的/
,因此我不必逃避斜杠:s/$/\/
也可以