Skip to content

Instantly share code, notes, and snippets.

@vcheckzen
Created August 13, 2024 16:49
Show Gist options
  • Save vcheckzen/133628e43f3818cd26ceb1fcdd8ff917 to your computer and use it in GitHub Desktop.
Save vcheckzen/133628e43f3818cd26ceb1fcdd8ff917 to your computer and use it in GitHub Desktop.
Reverse lines
#!/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"
}
@vcheckzen
Copy link
Author

$ 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment