Sco*_*len 591 unix shell command-line
我想颠倒文本文件(或stdin)中行的顺序,保留每行的内容.
所以,即从以下开始:
foo
bar
baz
Run Code Online (Sandbox Code Playgroud)
我想结束
baz
bar
foo
Run Code Online (Sandbox Code Playgroud)
是否有标准的UNIX命令行实用程序?
Mih*_*șan 1311
另外值得一提:( tac咳嗽,反向cat).部分的coreutils.
tac a.txt > b.txt
Run Code Online (Sandbox Code Playgroud)
Jas*_*hen 423
BSD尾巴:
tail -r myfile.txt
Run Code Online (Sandbox Code Playgroud)
参考:FreeBSD,NetBSD,OpenBSD和OS X手册页.
eph*_*ent 153
有着名的sed技巧:
# reverse order of lines (emulates "tac")
# bug/feature in HHsed v1.5 causes blank lines to be deleted
sed '1!G;h;$!d' # method 1
sed -n '1!G;h;$p' # method 2
Run Code Online (Sandbox Code Playgroud)
(说明:在非初始行前加上保持缓冲区,交换行和保持缓冲区,在末尾打印出行)
awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file*
Run Code Online (Sandbox Code Playgroud)
如果你不记得了,
perl -e 'print reverse <>'
Run Code Online (Sandbox Code Playgroud)
在具有GNU实用程序的系统上,其他答案更简单,但并非全世界都是GNU/Linux ...
Der*_*ike 59
如果你正好在vim使用中
:g/^/m0
Run Code Online (Sandbox Code Playgroud)
Dig*_*oss 42
$ (tac 2> /dev/null || tail -r)
Run Code Online (Sandbox Code Playgroud)
试试tac,适用于Linux,如果不起作用tail -r,可以在BSD和OSX上运行.
小智 41
tac <file_name>
Run Code Online (Sandbox Code Playgroud)
例:
$ cat file1.txt
1
2
3
4
5
$ tac file1.txt
5
4
3
2
1
Run Code Online (Sandbox Code Playgroud)
Yak*_*dry 41
在你的命令结束时:
| tac
tac完全符合您的要求,它"将每个文件写入标准输出,最后一行写入."
tac与猫相反:-).
小智 24
请尝试以下命令:
grep -n "" myfile.txt | sort -r -n | gawk -F : "{ print $2 }"
Run Code Online (Sandbox Code Playgroud)
kon*_*box 16
Just Bash :)(4.0+)
function print_reversed {
local lines i
readarray -t lines
for (( i = ${#lines[@]}; i--; )); do
printf '%s\n' "${lines[i]}"
done
}
print_reversed < file
Run Code Online (Sandbox Code Playgroud)
小智 11
最简单的方法是使用该tac命令.tac是cat反过来的.例:
$ cat order.txt
roger shah
armin van buuren
fpga vhdl arduino c++ java gridgain
$ tac order.txt > inverted_file.txt
$ cat inverted_file.txt
fpga vhdl arduino c++ java gridgain
armin van buuren
roger shah
Run Code Online (Sandbox Code Playgroud)
我真的很喜欢" 尾巴 "答案,但我最喜欢的gawk答案是....
gawk '{ L[n++] = $0 }
END { while(n--)
print L[n] }' file
Run Code Online (Sandbox Code Playgroud)
对于可能tac在 shell 脚本中使用的跨操作系统(即 OSX、Linux)解决方案,请使用上面提到的自制软件,然后像这样使用别名 tac:
安装库
对于 MacOS
brew install coreutils
Run Code Online (Sandbox Code Playgroud)
对于 linux debian
sudo apt-get update
sudo apt-get install coreutils
Run Code Online (Sandbox Code Playgroud)
然后添加别名
echo "alias tac='gtac'" >> ~/.bash_aliases (or wherever you load aliases)
source ~/.bash_aliases
tac myfile.txt
Run Code Online (Sandbox Code Playgroud)
如果你想就地修改文件,你可以运行
sed -i '1!G;h;$!d' filename
Run Code Online (Sandbox Code Playgroud)
这样就不需要创建临时文件,然后删除或重命名原始文件,并且具有相同的结果。例如:
$tac file > file2
$sed -i '1!G;h;$!d' file
$diff file file2
$
Run Code Online (Sandbox Code Playgroud)
基于ephemient 的答案,它几乎但不完全是我想要的。
| 归档时间: |
|
| 查看次数: |
309730 次 |
| 最近记录: |