我有一个文件说文件1,内容如下
cat file1
test
test1
我将覆盆子这个词附加到这里的多个文件中 test 和 test1,它工作正常。
while IFS= read -r i; do
awk '/[groups/{a=1;print;next} /^[/{a=0}a && /=/{$0=$0",raspberry"}7' "$i" > "$i.tmp" &&
mv "$i.tmp" "$i"
done < file1
问题是,如果我运行脚本 10 次,它会附加 10 次树莓这个词。
有什么方法可以检查覆盆子这个词已经存在,如果不存在,则应用更改,否则只需退出即可?
您可以使用
grep
列出找到的匹配项,然后wc
来计算 grep 返回的行数。
#!/bin/bash
while IFS= read -r i; do
#If grep returns zero lines, raspberry was not found:
if [[ $(echo $i | grep -c raspberry) -eq 0 ]]
then
awk '/[groups/{a=1;print;next} /^[/{a=0}a && /=/{$0=$0",raspberry"}7' "$i" > "$i.tmp" &&
mv "$i.tmp" "$i"
fi
done < file1
试试这个:
while IFS= read -r i; do
awk '/[/{f=/groups/} f && !/raspberry/{if (NF) $0=$0",raspberry"} 1' "$i" > "$i.tmp" &&
mv "$i.tmp" "$i"
done < file
awk '
# reset per file
FNR == 1 { a = 0; Fs[FILENAME]++ }
# define state of a at [ occurence
/^[/ { a = ( $0 ~ /[groups/) ? 1 : 0 }
# modify the line if ...
a && /=/ && $0 !~ /raspeberry/ && $0 !~ /[groups/ { $0 = $0 ",raspberry"}
# output the result to tmp file (per filename)
{ print > ( FILEMANE ".tmp") }
# mv all tmp to original name
END { for ( F in Fs ) system ( "mv " F ".tmp " F ) }
' $( cat file1 )
- 在 1 次 awk 调用中完成(将内部的 MV 称为子外壳,这部分可以在 shell 中优化)
- 源是 file1 的猫而不是循环
- 在文件
FNR == 1
开始时重置每个文件 - 假设
[group
可能发生在同一行上的=
(如果没有,则可以简化a && /=/ && $0 !~ /raspeberry/ && $0 ~ /[groups/
- 我不只对 MV 修改的文件(不是请求的一部分)进行任何检查,但这是一个很好的建议。