1. 程式人生 > 其它 >linux中sed命令實現任意兩行資料的互換

linux中sed命令實現任意兩行資料的互換

1、測試資料

[root@centos7pc1 test2]# cat test.txt
1 x c
2 s d
3 e t
4 d s
5 j u
6 n x

 

2、程式

[root@centos7pc1 test2]# cat swap.sh
#!/bin/bash
temp1=$(sed -n "$1p" $3)
temp2=$(sed -n "$2p" $3)
sed "$1c $temp2" $3 -i
sed "$2c $temp1" $3 -i

 

3、測試

[root@centos7pc1 test2]# ls
swap.sh  test.txt
[root@centos7pc1 test2]# cat test.txt    ## 測試資料
1 x c 2 s d 3 e t 4 d s 5 j u 6 n x [root@centos7pc1 test2]# cat swap.sh ## 程式 #!/bin/bash temp1=$(sed -n "$1p" $3) temp2=$(sed -n "$2p" $3) sed "$1c $temp2" $3 -i sed "$2c $temp1" $3 -i [root@centos7pc1 test2]# bash swap.sh 1 3 test.txt ## 1和3為交換的行號, test.txt為處理的檔案 [root@centos7pc1 test2]# ls swap.sh test.txt [root@centos7pc1 test2]# cat test.txt ## 檢視交換結果
3 e t 2 s d 1 x c 4 d s 5 j u 6 n x

 

[root@centos7pc1 test2]# ls
swap.sh  test.txt
[root@centos7pc1 test2]# cat test.txt
3 e t
2 s d
1 x c
4 d s
5 j u
6 n x
[root@centos7pc1 test2]# cat swap.sh   ## 程式
#!/bin/bash
temp1=$(sed -n "$1p" $3)
temp2=$(sed -n "$2p" $3)
sed "$1c $temp2" $3 -i
sed "$2c $temp1
" $3 -i [root@centos7pc1 test2]# bash swap.sh 2 5 test.txt ## 第2行和第5行進行互換 [root@centos7pc1 test2]# ls swap.sh test.txt [root@centos7pc1 test2]# cat test.txt ## 檢視交換結果 3 e t 5 j u 1 x c 4 d s 2 s d 6 n x