匹配后用参数替换路径

时间:2017-06-26 11:39:55

标签: bash sed

我想使用sed来替换一条路径不同的路径,

我有这个log4j文件:

# suppress inspection "UnusedProperty" for whole file
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
spark.log.path=/tmp/logs/spark
msg.layout=%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%t] (%F:%L) : %m%n

现在我想将" spark.log.path =" 之后的路径更改为新路径, log4j文件总是在变化,所以我不想替换路径字符串,我想在匹配' spark.log.path =' 之后替换路径

我尝试过这个shell脚本,但它不起作用(例外):

origin_path='spark.log.path='
k8s_path='spark.log.path=/tmp/logs/spark/master'
sed -i 's/^'${origin_path}' .*$/'${k8s_path}'/' log4j.properties

任何人都可以看到我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

只需更改分隔符:

sed -i "s_^${origin_path}.*_${k8s_path}_" log4j.properties

您与日志路径存在冲突。

答案 1 :(得分:0)

尝试:

awk -v new_path="spark.log.path=/tmp/logs/spark/master" '{sub(/spark.log.path.*/,new_path);print}'  Input_file > temp_file && mv temp_file Input_file

简单地将正则表达式spark.log.path。*替换为spark的新值,该值存在于awk的名为new_path的变量中,然后执行print。将所有行输出到temp_file中,一旦此命令成功完成,然后将temp_file重命名为Input_file。

PS:还有awk的版本也会对Input_file进行就地更新,上面的代码首先读取Input_file并进行更改解析并将预期输出转换为临时文件,然后将其重命名为相同INPUT_FILE。

相关问题