gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:21:42 26 4
gpt4 key购买 nike

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

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

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

我应该如何使用“while”遍历每个文件?

最佳答案

使用 Glob 填充循环变量

当您在当前目录上使用 -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

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

关于file - 如何使用循环从 .txt 文件中删除行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11595537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com