简体   繁体   English

如何递归查找特定文件并从linux中找到的所有文件中删除最后一行?

[英]How to find a specific file recursively and delete the last line from all files found in linux?

I want to find a specific file eg foo.txt recursively and delete the last line from it if the line contains a specific word (eg bar) .我想递归查找特定文件, eg foo.txt ,如果该行包含特定单词(eg bar) ,则从中删除最后一行。 Basically combine -基本上结合——

find . -type f -iname "foo.txt"
sed '$d' foo.txt
dir1 -
      |-sub-dir1-
                 |-foo.txt
      |-sub-dir2-
                 |-foo.txt
      |-
      .
      .
      |-
      |-sub-dirn-
                 |-foo.txt

Delete last line from all foo.txt files under dir1 if the last line contains bar .如果最后一行包含bar ,则从dir1下的所有foo.txt文件中删除最后一行。

Original contents -原创内容——

foo.txt
1
2
bar

After deletion -删除后——

foo.txt
1
2

Thanks.谢谢。

Use the -exec option to run the sed command.使用-exec选项运行sed命令。 Add the /bar/ regular expression to check that the last line also matches that pattern.添加/bar/正则表达式以检查最后一行是否也匹配该模式。

find . -type f -iname "foo.txt" -exec sed -i '${/bar/d;}' {} +

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从目录中递归找到的所有文件中搜索行匹配 - how to search for a line match from all files recursively found in a directory 如何使用Linux CLI查找一行代码并从特定/目录中的所有文件中删除该行 - How to find a line of code and delete that line from all files in a certain /directory only, using Linux CLI 通过从特定目录中递归搜索来从所有文本文件中提取最后一行 - Extract the last line from all text files by recursively searching from a specific directory (Linux) 用另一个文件中的数据递归地覆盖文件夹中的所有文件 - (Linux) Recursively overwrite all files in folder with data from another file 如何从Linux中的文本文件中获取第N行(特定行)和最后一行的组合? - How to get combination of Nth line(specific line) and last but one line from text file in Linux? 如何从linux中的特定文件夹中删除文件? - How to delete files from specific folders in linux? 如何删除除 linux bash 中按日期排序的最后 5 个文件以外的所有文件 - How to delete all files except last 5 ordered by date in linux bash 如何从 linux 文件中删除特定符号? - How To delete specific symbols from a linux file? Linux中查找和删除类似文件的命令行 - Command Line to find and delete Similar files in Linux 删除文件中包含字符串的文件 - Linux cli - Delete files with string found in file - Linux cli
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM