我怎样才能转换这个:
-foo -bar 42 \
randomtext=00 "00" \
-randomtext=00 "00" \
-foo -bar 104 \
randomtext=00 "00" \
-foo -bar 1 \
-randomtext=00 "00" \
对此:
-foo -bar 1 \
-randomtext=00 "00" \
-foo -bar 42 \
randomtext=00 "00" \
-randomtext=00 "00" \
-foo -bar 104 \
randomtext=00 "00" \
我想根据以下数值对线簇进行排序-酒吧
答案1
使用python
:
#!/usr/bin/env python2
import re, sys
list_of_lines = []
with open(sys.argv[1]) as f:
for line in f.read().split('-foo'):
if line:
list_of_lines.append(line)
for line in sorted(list_of_lines, key=lambda i: int(re.search(r'(?<=-bar )\d+', i).group())):
print '-foo' + line.rstrip()
输出 :
-foo -bar 1 \
-randomtext=00 "00" \
-foo -bar 42 \
randomtext=00 "00" \
-randomtext=00 "00" \
-foo -bar 104 \
randomtext=00 "00" \
如何运行:
将文件另存为例如script.py
,使其可执行,然后将您希望脚本操作的文件作为第一个参数传递:
/path/to/script.py /path/to/file.txt
如果脚本和文件位于同一目录中,则从该目录:
./script.py file.txt
您可以通过将脚本作为参数传递给可执行文件来运行它,而无需使其成为python
可执行文件:
python2 script.py file.txt
答案2
perl 方式:
#!/usr/bin/perl
$filename=$ARGV[0];
open(my $fh, "<", $filename) or die "cannot open < $filename: $!";
my %hash, my $key;
while (my $row = <$fh>) {
chomp $row;
if ($row =~ /\-bar\s+([0-9]+)/ ) {
$key = $1;
}
$hash{$key} .= "$row\n";
}
foreach (sort { $a <=> $b } keys(%hash) ) {print "$hash{$_}"}
保存脚本并调用可执行文件(chmod +x script
):
script file.txt
输出:
-foo -bar 1 \
-randomtext=00 "00" \
-foo -bar 42 \
randomtext=00 "00" \
-randomtext=00 "00" \
-foo -bar 104 \
randomtext=00 "00" \