我无法理解一个奇怪的行为:vi 似乎在文件末尾添加了一个换行符(ASCII:LF,因为它是 Unix ( AIX ) 系统),而我没有专门输入它。
我在 vi 中编辑文件(注意不要在最后输入换行符):
# vi foo ## Which I will finish on the char "9" and not input a last newline, then `:wq`
123456789
123456789
123456789
123456789
~
~
## When I save, the cursor is just above the last "9", and no newline was added.
Run Code Online (Sandbox Code Playgroud)
我希望 vi 将它“按原样”保存,因此有 39 个字节:前三行(数字 1 到 9,后跟一个换行符(我的系统上为 LF))中的每一行都有 10 个 ASCII 字符,最后一行只有 9 个行(字符 1 到 9,没有终止换行符/LF)。
但是当我保存它时出现它是40个字节(而不是 39 个),并且od 显示一个终止的 LF: …
[编辑:澄清我需要一个in awk解决方案,并更正我需要对“索引”进行排序(或者更确切地说,以排序方式输出它们)而不是模糊的“值”)]
在 awk 中,我经常计算事物,或者将一组值存储在一个数组中,使用这些值作为索引(利用 awk 的 index_are_hashes 机制)
例如:如果我想知道我遇到了多少个不同的 $2 值,以及每个值出现的频率:
awk '
... several different treatments ...
{ count[$2]++ }
... other treatments ...
END { for(str in count) {
print "counted: " str " : " count[str] " times."
... and other lines underneath, with additional infos ...
}
}
'
Run Code Online (Sandbox Code Playgroud)
问题在于(非 GNU 或其他更好的版本)常规 awk(和常规 nawk):
对于 [A]:不太难做.. 只需要另一个数组来索引“新看到的”条目。
问题适用于 [B]:如何进行简单的排序调用以重新排序不同索引的显示?
(注意:我知道 gnu awk 对 [B] 有一个“简单”的方法:https : //www.gnu.org/software/gawk/manual/html_node/Controlling-Array-Traversal.html …
测试用例:(使用非 root 用户,因为 root 会忽略 000 权限...)
#in a clean directory:
[ -f file_1 ] && chmod 600 file_? # for repeat tests...
for i in file_1 file_2 file_3; do
printf 'A\nB\n' > "$i"
# we need at least 1 char : awk/gawk silently skips empty files...
done
chmod 000 file_2
awk '(FNR==1) { print FILENAME }' file_?
# tried with : regular (old unixes) awk on AIX. and gawk on Linux.
# the fatal "permission denied" on file_2 stops …
Run Code Online (Sandbox Code Playgroud) 一些精度:
我试图以正确的顺序显示一些内容,因此我通过 shell 的“sort”和“uniq”管道输出...但我无法按照我编写的顺序获取输出。
麻烦的代码:
egrep -i "something_FREQUENT" BIGFILE | sort | awk -F',' '
{ servs=servs $1 " " ; groupe=groupe "\n " $2 ; }
END { print "Groupes (alphabetical order):" ;
printf groupe "\n" | "grep . | sort | uniq | xargs echo ";
print ; rem="extra newline to help buffering... does NOT help.";
system(""); rem="supposed to force flush of stdout... does NOT help.";
print "Servers:"
printf …
Run Code Online (Sandbox Code Playgroud)