shell三剑客过滤文件内字符串长度输出

三剑客过滤长字符串

记一次过滤文件内容,三剑客awk、grep、sed过滤指定字段、列后,怎料其中混杂编码字符串,这不是我们想要的。所幸,找到了规律,那就是 它 很长…,直接干掉长字符串即可! 下边是三把剑具体实现!

我有三把剑,一把awk,一把grep,一把sed

[root@centos]# cat test
hello
helloword
test66

awk式

  • 且看,统计字符串长度,用到招式 length() 函数
[root@centos]#  echo "hello" | awk '{print length($1)}'
5

如看官所愿,得到字符串的长度 5

  • 连招,加 if 语句,输出指定的字符串长度内容小于等于6的
[root@centos]# awk '{ if ( length($0) <=6 ) print $0}' test
hello
test66 

grep式

[root@centos]# egrep  -w '^.{1,6}'  test
hello
test66
  • egrep参数:相当于 grep -E ,用于匹配正则
  • -w参数:仅跟模式匹配的字符串
  • ^. 参数:表示以任意字符开头

sed式

[root@centos]# sed -n '/^.\{7,\}/!p'  test
hello
test66
  • -n参数:–silent,配合编辑命令只打印符合条件字符串
  • !p参数:符合条件的不打印,p即为打印输出
  • \参数:转义字符,转义 { }

各位看官,江湖再会!

原创文章 149 获赞 338 访问量 28万+

猜你喜欢

转载自blog.csdn.net/Sunny_Future/article/details/105799550