bash 如何使用循环从 .txt 文件中删除行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11595537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:50:40  来源:igfitidea点击:

How can I remove lines from .txt files using a loop?

filebashloopsedit

提问by Sara

In my current directory I have a couple of .txt files. I want to write a script to search for a string in those .txt files, and delete lines which contains that string. For example, I'd like to delete all lines which have the word "start" in all .txt files in my current directory.

在我当前的目录中,我有几个 .txt 文件。我想编写一个脚本来搜索那些 .txt 文件中的字符串,并删除包含该字符串的行。例如,我想删除当前目录中所有 .txt 文件中包含“start”一词的所有行。

I have written the following code, but I don't know how to continue!

我已经写了下面的代码,但我不知道如何继续!

#!bin\bash
files=`find . -maxdepth 1 -name \*.txt`

How should I use "while" to go through each file?

我应该如何使用“while”来浏览每个文件?

回答by Chirlo

Easy cheasy: sed -i "s/^.*string.*//" *.txtthis will remove any line containing 'string' on each .txt file

Easy cheasy: sed -i "s/^.*string.*//" *.txt这将删除每个 .txt 文件中包含“字符串”的任何行

回答by Todd A. Jacobs

Use Globs to Populate Loop Variables

使用 Glob 填充循环变量

When you use -maxdepth 1on the current directory, you aren't recursing into subdirectories. If that's the case, there's no need at all to use findjust to match files with an extension; you can use shell globsinstead to populate your loop constructs. For example:

-maxdepth 1当前目录上使用时,不会递归到子目录中。如果是这种情况,根本不需要使用find来匹配带有扩展名的文件;您可以使用shell globs来填充循环结构。例如:

#!/bin/bash

# Run sed on each file to delete the line.
for file in *txt; do
    sed -i '/text to match/d' "$file"
done

This is simple, and avoids a number of filename-related issues that you may have when passing filename arguments between processes. Keep it simple!

这很简单,并且避免了在进程之间传递文件名参数时可能遇到的许多与文件名相关的问题。把事情简单化!

回答by Ignacio Vazquez-Abrams

You use it along with readto get each filename in turn, after piping the results of findto it. Then you just pass the filename to sedto delete the lines you're interested in.

您可以使用它一起read拿到依次在每个文件名,管道后的结果find吧。然后您只需将文件名传递sed给删除您感兴趣的行。