TransWikia.com

How to Find & Replace a String Within Files with Find / Grep / Sed

Stack Overflow Asked by waiwai57 on January 16, 2021

I have a folder of 500 *.INI files that I need to manually edit. Within each INI file, I have the line Source =. I would like that line to become Source = C:software{filename}.

For instance, a dx4.ini file would need to be fixed to become: Source = C:softwaredx4

Is there a quick way to do this with Find, Grep, or Sed functions?

4 Answers

find *.ini -type -f > stack

while read line 
do
sed -i s"@Source =@Source = C:\software\dx4@" "${line}"
done < stack

Assuming that a} You have sed with "-i" (the insert flag, which AFAIK is not always portable) and b} sed doesn't crap itself about a double escape sequence, I think that will work.

Answered by petrus4 on January 16, 2021

With GNU awk for the 3rd arg to match(), gensub(), and "inplace" editing:

awk -i inplace '
    match($0,/(.*Source = C:\software\){filename}(.*)/,a) {
        fname = gensub(/..*/,"",1,FILENAME)
        $0 = a[1] fname a[2]
    }
1' *.INI

The above assumes you're running in a UNIX environment though your use of the term folder instead of directory and that path starting with C: and containing backslashes makes me suspicious. If you're on Windows then save the part between the 2 's (exclusive) in a file named foo.awk and execute it as awk -i inplace foo.awk *.INI or however it is you normally execute commands like this in Windows.

Answered by Ed Morton on January 16, 2021

If you want to edit a file in a script, I think ed is the way to go. Combined with a shell for loop:

for file in *.INI; do
    base=$(basename "$file" .INI)
    ed -s "$file" <<EOF
/^Source =/s/=/= C:\\software\\$base/
w
EOF
done

(This does assume that filenames will not have newlines or ampersands in their names)

Answered by Shawn on January 16, 2021

You can try with sed For example

Input file contents: file.txt

Source =
some lines..

script:

newstring='Source = C:softwaredx4'
oldstring='Source ='
echo `sed "s/$oldstring/$newstring/g" file.txt` > file.txt

After running the above commands output:

Source = C:softwaredx4
some lines..

Answered by coder here on January 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP