![](/img/trans.png)
[英]Remove text that is saved in a file, from multiple files in linux terminal
[英]Remove line of text from multiple files in Linux
有沒有一種簡單的方法可以從命令行中充滿文本文檔的文件夾中刪除相同的文本行?
如果你的sed版本允許-i.bak
標志(就地編輯):
sed -i.bak '/line of text/d' *
如果沒有,只需將其放入bash循環:
for file in *.txt
do
sed '/line of text/d' "$file" > "$file".new_file.txt
done
可以使用查找a pattern
並刪除the line containing the pattern
下面the line containing the pattern
find . -name "*" -type f | xargs sed -i -e '/<PATTERN>/d'
示例:如果要刪除所有xml
文件中包含單詞sleep
的行
find . -name "*.xml" -type f | xargs sed -i -e '/sleep/d'
注意:在選擇模式之前要小心,因為它會在當前目錄層次結構的所有文件中以遞歸方式刪除該行:)
考慮grep -v:
for thefile in *.txt ; do
grep -v "text to remove" $thefile > $thefile.$$.tmp
mv $thefile.$$.tmp $thefile
done
Grep -v顯示除匹配之外的所有行,它們進入臨時文件,然后將tmpfile移回舊文件名。
perl -ni -e 'print if not /mystring/' *
這告訴perl循環遍歷文件(-n),在適當位置編輯(-i),如果它與正則表達式不匹配則打印該行。
有點相關,這是一種方便的方式來執行多個文件的替換。
perl -pi -e 's/something/other/' *
我為此寫了一個Perl腳本:
#!/usr/bin/perl
use IO::Handle;
my $pat = shift(@ARGV) or
die("Usage: $0 pattern files\n");
die("Usage $0 pattern files\n")
unless @ARGV;
foreach my $file (@ARGV) {
my $io = new IO::Handle;
open($io, $file) or
die("Cannot read $file: $!\n");
my @file = <$io>;
close($io);
foreach my $line (@file) {
if($line =~ /$pat/o) {
$line = '';
$found = 1;
last;
}
}
if($found) {
open($io, ">$file") or
die("Cannot write $file: $!\n");
print $io @file;
close($io);
}
}
請注意,它會根據正則表達式刪除行。 如果你想做完全匹配,內部foreach
看起來像:
foreach $line (@file) {
chomp $line;
if($line eq $pat) {
$line = '';
$found = 1;
last;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.