如果这个问题之前被问过,我很抱歉,在这个问题上确实停留了几个小时,这看起来相对容易。我在单个文件中通过 awk 识别出了两个模式。
awk '/\[code\.change\..*\]/ {found=1; print; next} found && NF {print} found && !NF {exit}' filename
awk '/\[code\.test\..*\]/ {found=1; print; next} found && NF {print} found && !NF {exit}' filename
我是否可以将这两个 awk 合并为一个来交换块?
配置文件的示例如下 文件.cfg
[code.change.1]
file.path=filename
file.contact=manager
file.active=TRUE
[code.test.1]
ls -la filepath
pwd
find . -name filename
只需调换配置顺序即可。谢谢
根据提供的示例,请您尝试一下:
awk -v RS= ' # records are reparated by blank lines
/^\[code\.change/ {pos1 = NR} # position of the 1st block
/^\[code\.test/ {pos2 = NR} # position of the 2nd block
{
ary[NR] = $0 # store the record in an array
}
END {
tmp = ary[pos1]; ary[pos1] = ary[pos2]; ary[pos2] = tmp # swap the two records
for (i = 1; i <= NR; i++) print(ary[i], i<NR ? ORS : "") # print the array
}
' file.cfg