次のデータを含むファイルがあります。
BEGIN
hello2
5
world1
END
BEGIN
hello4
2
world5
END
BEGIN
hello6
4
END
ブロック内の数字に基づいて、次のように行をソートしたいと思います。この数字は別々でユニークです。
BEGIN
hello4
2
world5
END
BEGIN
hello6
4
END
BEGIN
hello2
5
world1
END
私はsedとawkを使ってブロックを印刷する方法を知っています。それはすべてです。
# Prints the blocks including the BEGIN and END tags
cat file | sed -n '/^BEGIN$/,/^END$/p'
# Prints the blocks exluding the BEGIN and END tags
awk '/^BEGIN$/ {show=1;next} /^END$/{show=0} { print }' file
ベストアンサー1
GNU awkを使う:
gawk '
BEGIN { RS="\nEND\n"; ORS = RS; FS = "\n" }
{ record[$3] = $0 }
END {
PROCINFO["sorted_in"] = "@ind_num_asc"
for (val in record) print record[val]
}
' file
あなたのデータによると、BEGINと数字の間には常に1行しかないと仮定しています。
このPROCINFO
行は、「records」配列を繰り返す方法を定義します。バラよりhttps://www.gnu.org/software/gawk/manual/html_node/Controlling-Scanning.html