linux 中grep命令匹配指定长度的字符串
1、
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt ## 测试数据 d xaa c xaaa d xaaaa e xaaaaa f xaaaaaa d dff gfgfgf e dfgdg gfdgedr d dfef fcgfg root@PC1:/home/test# grep -E -w "[^[:space:]]{3}" a.txt ## 长度为3 d xaa d dff gfgfgf root@PC1:/home/test# grep -E -w "[^[:space:]]{4}" a.txt ## 长度为4 c xaaa d dfef fcgfg root@PC1:/home/test# grep -E -w "[^[:space:]]{5}" a.txt d xaaaa e dfgdg gfdgedr d dfef fcgfg root@PC1:/home/test# grep -E -w "[^[:space:]]{7}" a.txt ## 长度为7 f xaaaaaa e dfgdg gfdgedr
2、awk实现
root@PC1:/home/test# ls a.txt root@PC1:/home/test# cat a.txt d xaa c xaaa d xaaaa e xaaaaa f xaaaaaa d dff gfgfgf e dfgdg gfdgedr d dfef fcgfg root@PC1:/home/test# awk '{for(i = 1; i <= NF; i++) {if(length($i) == 3) printf("%s\n", $0)}}' a.txt ## 输出长度为3的行 d xaa d dff gfgfgf root@PC1:/home/test# awk '{for(i = 1; i <= NF; i++) {if(length($i) == 4) printf("%s\n", $0)}}' a.txt ## 长度为4 c xaaa d dfef fcgfg root@PC1:/home/test# awk '{for(i = 1; i <= NF; i++) {if(length($i) == 5) printf("%s\n", $0)}}' a.txt ## 长度为5 d xaaaa e dfgdg gfdgedr d dfef fcgfg