簡體   English   中英

在Linux中將文件排序為注釋

[英]Sorting a file up to a comment in Linux

說我有一個sort_me.txt文件:

a
d
b
c
f
g

// dont mix the two sections

a
c
d 
b

目前,我進行了顯而易見的sort sort_me.txt並且得到:

a
a
b
b
c
c
d
d
// dont mix the two sections 
f
g

當然,這不是我想要的,我想要的是將其分別放在注釋之前的部分和注釋之后的部分中。

預期結果為:

a
b
c
d
f
g
// dont mix the two sections
a
b
c
d

Perl解救:

perl -007 -nE '
    @sections = map [ split /\n/ ], split m{^(?=//)}m;
    say join "\n", sort @$_ for @sections;
' -- file
  • -007讀取整個文件,而不是逐行處理(僅在文件不大的情況下有效)
  • @sections是一個數組數組,外部數組對應於節,內部數組對應於@sections

如果文件太大而無法放入內存,則需要逐行處理它,僅存儲當前部分:

perl -ne '
    sub out { print sort @lines; @lines = $_ }
    if (m{^//}) { out() }
    else { push @lines, $_ }
    END { out() }
' -- file

如果沒有perl,則可以使用以下腳本來實現:

#!/bin/bash

FILE_NAME=$1

SEPARATOR='//'

LINE_NUMBER=`grep -n $SEPARATOR $FILE_NAME  | cut -f1 -d:`

FILE_LENGTH=`wc -l $FILE_NAME | cut -f1 -d\s`

head -$(($LINE_NUMBER-1)) $FILE_NAME | sort

grep $SEPARATOR $FILE_NAME

tail -$(($FILE_LENGTH-$LINE_NUMBER-1)) $FILE_NAME | sort

它搜索分隔線並逐個對部分進行排序。 當然,如果您有兩個以上的部分,則將無法使用。

我當時正在考慮使用csplit將這些部分拆分為單獨的文件,但是當然應該有更簡單的方法來實現此目的:

#!/bin/bash

linenum=`csplit -z $1 /^$/ {*}`
count=0
output=''
for line in $linenum
  do
    file=`printf "xx%.2d" $count`
    sorted=`cat $file | sort`
    output="$output$sorted"
    ((count++))
  done
echo "$output"

注意, csplit將為每個部分創建一個臨時文件,因此您可以更新上述腳本以取消鏈接每個unlink $file ,即unlink $file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM