linux中提取包含指定字符的列
001、测试数据
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 1 2 3 4 5 6 7 8 9 e f s f g u d f x a d s g s c s e s z c b e g c s d f
002、提取包含自定字符的索引
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt 1 2 3 4 5 6 7 8 9 e f s f g u d f x a d s g s c s e s z c b e g c s d f root@PC1:/home/test# awk '{for(i = 1; i <= NF; i++) {if($i == "s") print i}}' a.txt 3 3 5 7 9 7 root@PC1:/home/test# awk '{for(i = 1; i <= NF; i++) {if($i == "s") print i}}' a.txt | sort | uniq 3 5 7 9 root@PC1:/home/test# awk '{for(i = 1; i <= NF; i++) {if($i == "s") print i}}' a.txt | sort | uniq > index.txt
003、生成过度文件
root@PC1:/home/test# ls a.txt index.txt root@PC1:/home/test# cat a.txt 1 2 3 4 5 6 7 8 9 e f s f g u d f x a d s g s c s e s z c b e g c s d f root@PC1:/home/test# cat index.txt 3 5 7 9 root@PC1:/home/test# for i in `cat index.txt`; do awk -v a=$i '{print $a}' a.txt | paste -d " " -s >> temp.txt; done root@PC1:/home/test# ls a.txt index.txt temp.txt root@PC1:/home/test# cat temp.txt 3 s s b 5 g s g 7 d s s 9 x s f
004、将过度文件转置
root@PC1:/home/test# ls a.txt index.txt temp.txt root@PC1:/home/test# cat temp.txt 3 s s b 5 g s g 7 d s s 9 x s f root@PC1:/home/test# for i in $(seq $(head -n 1 temp.txt | awk '{print NF}')); do cut -d " " -f $i temp.txt | paste -d " " -s >> result.txt; done root@PC1:/home/test# ls a.txt index.txt result.txt temp.txt root@PC1:/home/test# cat result.txt 3 5 7 9 s g d x s s s s b g s f