PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 2, 2022

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

 November 02, 2022     bash, edit, file, loops     No comments   

Issue

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.

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?


Solution

Use Globs to Populate Loop Variables

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

#!/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!



Answered By - Todd A. Jacobs
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing