sed指令實踐---用於排序
使用sed命令,進行簡單排序,更改源文件
首先,要排序的文件叫TestFile
[[email protected] shell]# cat TestFile
A:4
B:5
C:1
D:3
E:2
字母後邊是序號,要按照正確的12345順序排列。
腳本名字叫setup.sh
[[email protected] shell]# cat sed.sh
#!/bin/bash
TestFile=/home/craft/shell/TestFile
Testcontent=`awk -F: ‘{print $2}‘ $TestFile` 拿到第二列
echo $Testcontent
for init in $Testcontent;do
temp0=$(grep $init $TestFile |awk -F: ‘{print $1}‘) 拿到第一列
sed -i ‘/‘"$init"‘/a‘"$temp0"‘‘ test
done
原來test文件裏面,是序號12345
以A:4舉例 , init=4,用sed指令,把A查到test的第四列後
同樣的把B查到第5列後,進行排序。
運行sed.sh的結果是
[[email protected] shell]# ./sed.sh
4 5 1 3 2
test的內容變成
[[email protected] shell]# cat test
1
C
2
E
3
D
4
A
5
B
6
如果不用插入,用替換 sed -i ‘/‘"$init"‘/c"$temp0"‘‘ test
結果如下
[[email protected] shell]# cat test
C
E
D
A
B
另外,這個功能用sort就可以實現
[[email protected] shell]# sort +1 -2 -n -t : TestFile
C:1
E:2
D:3
A:4
B:5
sed指令實踐---用於排序