1. 程式人生 > >[sed] 保持空間

[sed] 保持空間

保持空間 Holding Space

-bash-4.1$ cat d09
1
2
11
22
111
222
-bash-4.1$
-bash-4.1$ sed '/1/{H;$!d};$p;$x' d09
2
22
222

1
11
111
-bash-4.1$
-bash-4.1$ sed '/2/{H;$!d};$x' d09
1
11
111

2
22
222
-bash-4.1$
-bash-4.1$ sed 'H;$!d;${x;s/^\n//;s/\n/,/g}' d09
1,2,11,22,111,222
-bash-4.1$
-bash-4.1$ function join_lines()
> {
>   sed 'H;$!d;${x;s/^\n//;s/\n/,/g}' $1
> }
-bash-4.1$ join_lines d09
1,2,11,22,111,222
-bash-4.1$
-bash-4.1$ function join_lines()
> {
>   local delim=${1:-,}
>   sed 'H;$!d;${x;s/^\n//;s/\n/'$delim'/g}'
> }
-bash-4.1$ cat d09 | join_lines ';'
1;2;11;22;111;222
-bash-4.1$
-bash-4.1$ function join_lines()
> {
>   local delim=${1:-,}
>   sed 'H;$!d;${x;s/^\n//;s/\n/\'$delim'/g}'
> }
-bash-4.1$ cat d09 | join_lines '&'
1&2&11&22&111&222
-bash-4.1$

為了理解 ${1:-,} 可以參考這裡

注意以&作為分隔符時必須利用 反斜槓\ 加以轉義。

關於sed的保持空間,可以參考這裡