2014-02-23 25 views
-1

這是我第一篇文章,在此先感謝您的及時支持。殼牌:用兩條特定線條之間的空格替換 n

我在一個大文件上做了一些greps,並且像下面的文件一樣。我想在同一行中以XX @開頭的所有行。

所以,我想流動:

[email protected]> 
Feb 23 07:00:03 
Feb 23 07:00:05 
Sent : 4608 
Received : 4227 
Feb 23 07:00:07 
Feb 23 07:00:09 

[email protected]> 
Feb 23 07:00:32 
Feb 23 07:00:34 
Sent : 4608 
Received : 4232 
Feb 23 07:00:36 
Feb 23 07:00:38 

[email protected]> 
Feb 23 08:00:03 
Feb 23 08:00:06 
Sent : 4608 
Received : 4265 
Feb 23 08:00:07 
Feb 23 08:00:09 

[email protected]> 
... 

要成爲:

[email protected]> Feb 23 07:00:03 Feb 23 07:00:05 Sent : 4608 Received : 4227 Feb 23 07:00:07 Feb 23 07:00:09 

[email protected]> Feb 23 07:00:32 Feb 23 07:00:34 Sent : 4608 Received : 4232 Feb 23 07:00:36 Feb 23 07:00:38 

[email protected]> Feb 23 08:00:03 Feb 23 08:00:06 Sent : 4608 Received : 4265 Feb 23 08:00:07 Feb 23 08:00:09 

[email protected]> ... 

回答

0

你可以做到這一點與AWK很容易地:

awk '/^XX/{if(length(out))print out;out=$0;next}{out=out" "$0}END{print out}' yourfile 

,說..如果行以「XX」開頭,則打印我們已經累積在變量中的任何內容,然後將當前行保存在變量out中。如果該行是其他內容,請在添加空格後將其附加到變量out。最後,打印我們在變量out中積累的內容。

輸出:

[email protected]> Feb 23 07:00:03 Feb 23 07:00:05 Sent : 4608 Received : 4227 Feb 23 07:00:07 Feb 23 07:00:09 
[email protected]> Feb 23 07:00:32 Feb 23 07:00:34 Sent : 4608 Received : 4232 Feb 23 07:00:36 Feb 23 07:00:38 
[email protected]> Feb 23 08:00:03 Feb 23 08:00:06 Sent : 4608 Received : 4265 Feb 23 08:00:07 Feb 23 08:00:09 
0

或者你也可以做到這一點慶典在大致相同的方式AWK我在其他答案:

#!/bin/bash 
while read line 
do 
    if [[ $line == XX* ]] ;then 
     echo $OUT   # Output whatever we have accumulated in $OUT 
     OUT=$line   # Zero out $OUT and restart accumulating 
    else 
     OUT="$OUT $line" # Append this line to $OUT 
    fi 
done < yourfile 
echo $OUT    # Output any trailing stuff at the end 
0
sed -n ' 
    # use -n to prevent sed from printing each line 
    # if the line read starts with XX, go (b) to :printit 
    /^XX/ b printit 
    # if it is the last line ($), also go to :printit 
    $ b printit 
    # for all other lines, append the read line to the hold space (H) 
    # and then go to the :end (so we read the next line) 
    H; b end 

:printit { 
    # swap the hold and the pattern space 
    x 
    # replace all (s/../../g) single or multiple newlines (\n\n*) 
    # with a space 
    s/\n\n*/ /g 
    # print the pattern space 
    p 
} 

:end 
' your_file