Sed分隔符不和Grep打得不错 [英] Sed delimiter not playing nice with Grep

查看:123
本文介绍了Sed分隔符不和Grep打得不错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用grep和sed结合使用时,只要使用标准的正斜杠分隔符,一切都可以。

  find 。 -maxdepth 2 -xdev -type f -exec grep -iteststring-l {} \; -exec sed -i'/./d'{} \; 

如果我将其更改为另一个字符(如+或#),则不起作用(我需要改变它,因为teststring可能包含/字符并导致错误。

  find。-maxdepth 2 -xdev -type f -exec grep -iteststring-l {} \; -exec sed -i'#。#d'{} \; 

是否存在这个问题?

解决方案

你试图清空任何包含testtring的文件,那就是:

  find。-maxdepth 2 -xdev  - 键入f | 
,而IFS =读取-r文件;执行
if grep -iteststring-q$ file; then
>$ file
fi
done

如果您想删除那些至少包含一个字符的行, 'd be:

  find。-maxdepth 2 -xdev -type f | 
IFS = read -r file ;如果grep -iteststring做
- q$ file;然后
sed -i'/^./d'$ file
fi
done

如果你想删除那些包含一些字符串foo的行,那就是:

  find。 -maxdepth 2 -xdev -type f | 
,而IFS =读取-r文件;做
if grep -iteststring-q$ file;然后
sed -i'/ foo / d'$ file
fi
done

只要遵循该模式,无论您想要做什么都很简单,假定您没有包含换行符的文件名。如果你喜欢,你可以将grep移动到find行,但看起来有点没有意义并且混淆了代码。


When using grep in conjunction with sed, everything is ok as long as the standard forward slash delimiters are used.

find . -maxdepth 2 -xdev -type f -exec grep -i "teststring" -l {} \; -exec sed -i '/./d' {} \;

If I change this to another character like "+" or "#", it doesn't work (I need to change this because the teststring may contain the "/" character and cause an error.

find . -maxdepth 2 -xdev -type f -exec grep -i "teststring" -l {} \; -exec sed -i '#.#d' {} \;

Is there away around this problem?

解决方案

It looks like you're trying to empty any files that contain teststring. That'd simply be:

find . -maxdepth 2 -xdev -type f | 
while IFS= read -r file; do
   if grep -i "teststring" -q "$file"; then
      > "$file"
   fi
done

If you want to just delete those lines that contain at least one character then that'd be:

find . -maxdepth 2 -xdev -type f | 
while IFS= read -r file; do
   if grep -i "teststring" -q "$file"; then
      sed -i '/^./d' "$file"
   fi
done

If you want to delete those lines that contain some string "foo" then that'd be:

find . -maxdepth 2 -xdev -type f | 
while IFS= read -r file; do
   if grep -i "teststring" -q "$file"; then
      sed -i '/foo/d' "$file"
   fi
done

Just follow that pattern and whatever you want to do is trivial, assuming you don't have file names that contain newlines. You could move the grep into the find line if you like, but it seems kinda pointless and obfuscates the code.

这篇关于Sed分隔符不和Grep打得不错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆