应在所需位置更新命令行输出

时间:2017-01-17 10:07:58

标签: awk sed

我在testfile.txt中有以下内容。

[client]

clientName = 

[servername]

targetUri = contact support team

该文件应使用hostname -s行末clientName =的输出进行更新,并且应在targetUri =末尾更新example.com,删除"联系支持团队"。

2 个答案:

答案 0 :(得分:1)

试试这个oneliner:

sed "/^clientName\b/{s/=.*/= $(hostname -s)/};/^targetUri\b/{s/=.*/= example.com/}" file

答案 1 :(得分:0)

@Sai,试试以下:

awk -vHOST=$(hostname -s) '/clientName =/{print $0 FS HOST;;next} /targetUri/{gsub(/contact support team/,HOST,$0);print;next} 1' Input_file > temp_file && mv temp_file  Input_file

所以在这里我用clientName =替换它的值和框的名称以及(联系支持团队)字符串的值与框的名称,然后我放将其转换为临时文件,然后将该临时文件重命名为真正的Input_file。

编辑:根据OP的代码更改一些代码。

awk -vHOST=$(hostname -s) '/clientName =/{$0=$0 FS HOST;print;next} /targetUri/{gsub(/contact support team/,"example.com",$0);print;next} 1' Input_file > temp_file && mv temp_file  Input_file

EDIT2: @Sai,请仔细阅读以下内容。

awk -vHOST=$(hostname -s)    #### creating a variable named HOST whose value is command's hostname -s's value.
 '/clientName =/             #### searching for string clientName = in every line and if this string found then do following.
{print $0 FS HOST            #### printing the value of current line along with the FS field separator with value of HOST variable here.
;next}                       #### putting next here for skipping all further statements here.
/targetUri/                  #### search for string targetUri for every line and if string found in any line then do following.
{gsub(/contact support team/,"example.com",$0);  #### substitute the value of string (contact support team) to "example.com" in that line then.
print;                                           #### print the newly formed line(which as example.com value in it).
next                                             #### using next keyword I am requesting awk not to proceed with further statements now.
} 1'                         #### awk works on condition{action} method, so if any condition is TRUE then action following it should work
                                  so by putting 1 I am making condition as TRUE and not mentioning any action so by default action print will happen.
Input_file > temp_file       #### put all the processed output into temp_file file.
&& mv temp_file  Input_file  #### &&(if previous awk command ran successfully then do this command) rename temp_file to Input_file now.