我有一个像下面这样的文件,并且需要grep以system_props(^ system_props)开头的行。
JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`
system_props="$system_props -sensu.controller.hostName=abc.nam.net"
system_props="$system_props -sensu.controller.port=8181"
system_props="$system_props -sensu.controller.node=Mcagent"
if [ -z "$JAVA_HOME" ]; then
if [ -d "/opt/middleware" ]; then
JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
fi
fi
我还有另一个名为file2的文件,其内容如下所示。
JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`
system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"
if [ -z "$JAVA_HOME" ]; then
if [ -d "/opt/middleware" ]; then
JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
fi
fi
现在我的要求是将cat file1 | grep ^system_props
的内容替换为cat file2 | grep ^system_props)
两个system_props值的预期输出应该相同,并在file1中追加缺失的行
答案 0 :(得分:1)
编辑: :由于OP更改了要求,因此请在此处添加已编辑的解决方案。
awk '
FNR==NR{
if(match($0,/^system_props=".*/)){
a[++count]=substr($0,RSTART+14,RLENGTH-14)
}
next
}
match($0,/^system_props="/){
$0=substr($0,RSTART,RLENGTH) a[++count1]
}
1;
END{
if(count!=count1){
while(++count1<=count){
print a[count1]
}
}
}
' File2 File1
能否请您尝试以下。这将通过字符串system_props
的出现将一个文件中的值替换为另一个文件,这意味着File2中第一次出现的字符串将被放置在File1中第一次出现的字符串中。
awk '
FNR==NR{
if(match($0,/^system_props=".*/)){
a[++count]=substr($0,RSTART+14,RLENGTH-14)
}
next
}
match($0,/^system_props="/){
$0=substr($0,RSTART,RLENGTH) a[++count1]
}
1
' Input_file2 Input_file1
对于您显示的示例,输出将如下所示。
JAVA_HOME=`find "$AGENT_HOME/jre" -name release -type f 2>/dev/null | sed "s|/release||g"`
system_props="$system_props -sensu.controller.hostName=testhost.net"
system_props="$system_props -sensu.controller.port=8080"
if [ -z "$JAVA_HOME" ]; then
if [ -d "/opt/middleware" ]; then
JAVA_HOME=`find /opt/middleware -type d -name jre 2>/dev/null | grep WebSphere | grep java | grep -v grep | sort | uniq`
fi
fi
说明: :添加了上述代码的详细说明。
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition if FNR==NR which will be TRUE when file2 is being read.
if(match($0,/^system_props=".*/)){ ##Checking condition if line has system_props=" then do following.
a[++count]=substr($0,RSTART+14,RLENGTH-14) ##Creating array a with index variable count(whose value is increasing with 1) and its value is substring of current line with starting point of RSTART and ending point of RLENGTH.
}
next ##next will skip all further lines from here.
}
match($0,/^system_props="/){ ##Checking condition if a line starts from
$0=substr($0,RSTART,RLENGTH) a[++count1] ##Assigning substring of current line from RSTART to RLENGTH and putting value of array a which we collected from previous file.
}
1 ##1 will print edited/non-edited lines of Input_file1 here.
' File2 File1 ##Mentioning Input_file names here.