Linux文本处理

整理Linux文本处理脚本

Posted by Cheney.Yin on November 3, 2024

Linux文本处理

多行连接

1
2
3
4
5
6
7
8
> for e in `seq 1 7`; do echo $e; done                                       
1
2
3
4
5
6
7

使用sed正序连接

1
2
> for e in `seq 1 7`; do echo $e; done | sed -n '1h;1!H;1!g;$!d; s/\n/,/g; p'
1,2,3,4,5,6,7

或者

1
2
> for e in `seq 1 7`; do echo $e; done | sed ':a;N;$!ba;s/\n/,/g' 
1,2,3,4,5,6,7

使用sed逆序连接

1
2
> for e in `seq 1 7`; do echo $e; done | sed '1!G;h;$!d; s/\n/,/g'
7,6,5,4,3,2,1

使用tr正序连接

1
2
> for e in `seq 1 7`; do echo $e; done | tr -s '\n' ',' | sed 's/,$//'
1,2,3,4,5,6,7

使用tr逆序连接

1
2
> for e in `seq 1 7`; do echo $e; done | tr -s '\n' ',' | sed 's/,$//' | rev
7,6,5,4,3,2,1

使用awk正序连接

1
2
> for e in `seq 1 7`; do echo $e; done | awk 'ORS=","' | sed 's/,$//'       
1,2,3,4,5,6,7

使用awk逆序连接

1
2
> for e in `seq 1 7`; do echo $e; done | awk 'ORS=","' | sed 's/,$//' | rev
7,6,5,4,3,2,1