我有一个日志文件我试图注释掉与我的数组不匹配的行。我成功地学习了如何创建一个数组,我可以回显数组项目,但是我无法接受任何与我的数组不匹配的东西并在它前面添加一些东西。这是我的代码,如果你有关于另一条路径的建议或我可以做得更好的方法:
for itsSaturday in $(find "$LOCATION" -mindepth 1 -maxdepth 1 -name "*.log" ); do
TEMPFILE="$itsSaturday.$$"
declare -a someArray=( "breakfast" "scrambled eggs" "Bloody Mary" )
theCall='some_additional_text_'
commentOn="## You_need_"
for arrayItem in "${someArray[@]}"; do
merged="$theCall$arrayItem"
if ! grep -q "$merged" "$itsSaturday"; then
sed -e '/$merged/! s:$commentOn$theCall::g' "$itsSaturday" > $TEMPFILE && mv $TEMPFILE "$itsSaturday"
fi
done
done
文件:
some_additional_text_breakfast
some_additional_text_bacon
some_additional_text_scrambled eggs
some_additional_text_Bloody Mary
some_additional_text_orange juice
some_additional_text_breakfast
归档:
some_additional_text_breakfast
## You_need_some_additional_text_bacon
some_additional_text_scrambled eggs
some_additional_text_Bloody Mary
## You_need_some_additional_text_orange juice
some_additional_text_breakfast
如何在与我的数组不匹配的项之前添加变量?
答案 0 :(得分:0)
尝试用以下内容替换内部for循环:
PROG=$(printf '%s\n' "${COMMENT[@]}" | while read comment ; do
/bin/echo -n '$0 !~ /'"$comment"'$/ && '
done
echo '1 { printf commentOn } ; { print }')
awk -v commentOn="$commentOn" "$PROG" $itsSaturday > $TEMPFILE && mv $TEMPFILE $itsSaturday
在每个文件上,这将创建一个执行工作的awk程序。
答案 1 :(得分:0)
我不喜欢使用bash
和sed
执行此操作,但我认为以下内容可能就够了:
#! /bin/bash
declare -a someArray=( "breakfast" "scrambled eggs" "Bloody Mary" )
theCall='some_additional_text_'
commentOn="## You_need_"
OIFS="$IFS"
IFS='|' mergedLines="${someArray[*]/#/$theCall}"
IFS="$OIFS"
for i in *.txt
do
TEMPFILE="$i.$$"
sed -r "/$mergedLines/!s/^/$commentOn/" "$i" >> "$TEMPFILE"
done
"${someArray[*]/#/$theCall}"
使用bash字符串替换将$theCall
的内容附加到数组中的每个元素。IFS='|' mergedLines="${someArray[*]}
是将数组元素组合成以管道分隔的字符串的便捷技巧。合并,(2)和(3)让我
some_additional_text_breakfast|some_additional_text_scrambled eggs|some_additional_text_Bloody Mary
在mergedLines
。
sed
(|
)中使用扩展正则表达式并替换不匹配的行。sed
模式使用单引号,因此其中的变量未展开。