Created
August 13, 2024 16:49
-
-
Save vcheckzen/133628e43f3818cd26ceb1fcdd8ff917 to your computer and use it in GitHub Desktop.
Reverse lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
reverse_all() { | |
input_file="$1" | |
# shellcheck disable=SC2016 | |
sed '2,$G;h;$!d' "$input_file" | |
} | |
reverse_inner_group_by_prefix() { | |
input_file="$1" | |
prefix_sep="$2" | |
# reverse lines in each group while preserving group order | |
awk -F"$prefix_sep" ' | |
{ | |
# Use the prefix (up to the comma) as the key | |
prefix = $1 | |
# Remove leading and trailing whitespace from the prefix | |
prefix = gensub(/^[ \t]+|[ \t]+$/, "", "g", prefix) | |
# Append the line to the corresponding prefix | |
lines[prefix] = lines[prefix] "\n" $0 | |
# Track the first occurrence of each prefix | |
if (!(prefix in seen)) { | |
order[++count] = prefix | |
seen[prefix] = 1 | |
} | |
} | |
END { | |
# Loop over the prefixes in the order they were first seen | |
for (i = 1; i <= count; i++) { | |
key = order[i] | |
# Print lines in reverse order for each group | |
split(lines[key], arr, "\n") | |
for (j = length(arr); j > 0; j--) { | |
if (arr[j] != "") print arr[j] | |
} | |
} | |
}' "$input_file" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ cat file g1 i1 g1 i2 g1 i3 g2 i1 g2 i2 g2 i3 $ reverse_all file g2 i3 g2 i2 g2 i1 g1 i3 g1 i2 g1 i1 $ reverse_inner_group_by_prefix file ' ' g1 i3 g1 i2 g1 i1 g2 i3 g2 i2 g2 i1