Peppershaker
Peppershaker

Reputation: 121

How to refer to glob expanded file name in bash?

Looking for a general solution to referring to glob expanded file names.

suppose I have 2 existing files. a.txt and b.txt, each containing the word hello.

Is it possible to do a 1 liner to replace hello with world across both files and overwrite them? a.txt and b.txt should all contain world.

Not sure how to refer to the expanded file names.

cat *.txt | sed 's/hello/world/g' > expandedFileName

What should I put in place of expandedFileName?

I want to overwrite the existing original file.

Upvotes: 2

Views: 367

Answers (1)

Shawn
Shawn

Reputation: 52334

You can use a tool like ed to edit the files you're interested in in-place:

for file in [ab].txt; do
    printf '%s\n' 'g/hello/s/hello/world/g' w | ed -s "$file"
done

will change every occurrence of hello to world in a.txt and b.txt and save the changed files.

Or using perl and its in-place editing mode:

perl -pi -e 's/hello/world/g' [ab].txt

Some versions of sed also support an -i option for in-place editing, but it's non-standard and whether or not it takes a mandatory or optional argument depends on the implementation, so I don't recommend it for a general solution.

Upvotes: 2

Related Questions