Exclude all lines match a pattern using ls and grep

本文探讨了在不同Shell环境中仅使用ls命令或结合grep命令来排除特定模式的文件列表的方法。通过示例展示了bash与ksh之间的差异,并比较了这两种解决方案的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    It is easy to to list all lines that match the pattern, but difficult tolist all lines except those that match the pattern.

We can only use ls or joined with grep to get this goal.

(1) Only using ls

bash:

-----------------------------------------------------------

bash-2.05$ ls                               

aa.txt  ab.txt  bb.txt

bash-2.05$ ls [^a]*                          /* success */

bb.txt

bash-2.05$ ls !(a*)                          /* fail */

bash: !: event not found

bash-2.05$ ls *^b.txt$                       /* fail */

*^b.txt$: No such file or directory

-----------------------------------------------------------

 

ksh:

-----------------------------------------------------------

$ ls

aa.txt  ab.txt  bb.txt

$ ls [^a]*                                   /* fail */

aa.txt  ab.txt

$ ls !(a*)                                   /* success */

bb.txt

$ ls *^b.txt$                                /* fail */

*^b.txt$: No such file or directory

-----------------------------------------------------------

we can see from above that different shell works in different way.

(2) Joined with grep

$ ls

aa.txt  ab.txt  bb.txt

$ ls|grep -v aa*

ab.txt

bb.txt

$ ls|grep -v aa*|grep -v bb*

ab.txt

$ ls | /usr/xpg4/bin/grep -v -E 'aa.*|bb.*'

ab.txt

$

(3) Comparison of these two solutions

 Solution 1 only using ls is fit to some special situation, such as ftp. Because in ftp we can’t use pipe, that is we can’t use solution2.

 But solution 1 is shell dependence. And it’s difficult to realize combine condition, such 'aa.*|bb.*'.

 Solution 2 is easy to realize combine condition, such as 'aa.*|bb.*'.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值