比賽

2017-06-26 169 views
0

後的參數替換路徑我想使用的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 

任何人都可以看到我失去了什麼?

+0

除了使用[不同分隔符](https://stackoverflow.com/documentation/sed/1096/substitution/12280/using-different-delimiters#t=201706261148032439234)以避免與搜索和替換中的'/'發生衝突字符串,你還需要[escape metacharacters](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed)like'.' – Sundeep

回答

1

只要改變分離:

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

您有衝突VS日誌路徑。

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 *到火花的新價值這是目前new_path命名然後做打印awk的變量。將所有行輸出到temp_file中,一旦該命令成功完成,則將temp_file重命名爲Input_file。

PS:這裏有awk的版本,它們也會對Input_file進行就地更新,上面的代碼讀取第一個Input_file,並對更改進行解析並將預期輸出轉換爲臨時文件,然後將其重命名爲相同的Input_file。