Solved

How do I search and replace text in a batch of files?

Posted on 2006-10-26
3
399 Views
Last Modified: 2010-04-21
In a folder I have about 150 files. I want to search for all instances of header.txt and replace it with header_lu.txt. Is this possible thru the a command? Thanks in advance for all the help.
0
Comment
Question by:bemara57
3 Comments
 
LVL 14

Accepted Solution

by:
chris_calabrese earned 500 total points
ID: 17812249
Like anything in Unix, there are many ways to skin this cat.

Here is one that might work for you:

tmpfile="$(mktemp -c -p "replacement")"
<find or ls to get list of files on stdout> | while read file
do
    awk '{
        gsub(/header[.]txt/, "header_lu.txt", $0)
        print $0
        }' < "$file" > "$tmpfile"
    cat "$tmpfile" > "$file"
done
rm -f "$tmpfile"
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 17812787
Hi bemara57,

find /path/to/folder | while read fname
do
      sed 's/header\.txt/header_lu\.txt/g' $fname > $fname.new
      mv -f $fname.new $fname
done

Cheers!
sunnycoder
0
 
LVL 84

Expert Comment

by:ozo
ID: 17813076
perl -i -pe 's/header\.txt/ header_lu.txt/g' folder/*
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Let's say you need to move the data of a file system from one partition to another. This generally involves dismounting the file system, backing it up to tapes, and restoring it to a new partition. You may also copy the file system from one place to…
A metadevice consists of one or more devices (slices). It can be expanded by adding slices. Then, it can be grown to fill a larger space while the file system is in use. However, not all UNIX file systems (UFS) can be expanded this way. The conca…
Learn how to find files with the shell using the find and locate commands. Use locate to find a needle in a haystack.: With locate, check if the file still exists.: Use find to get the actual location of the file.:
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now