-1

I have numerous files in a directory and want to replace one of the libraries used in all of these files with a newer library because the old library no longer works.

I have used ls > names.txt to list all filenames into a txt document. I then attempted to write a bash script which would loop through all files, catch the old library, and replace it with the new library.

for entry in names.txt
do
    sed 's/<libOld>/<libNew>/g' $entry > $entry
done

I expect the loop to go through each file name, find the old library used, and replace it with the new one. Running this script however doesn't appear to do anything.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116

1 Answers1

0

You're bumping into a few common issues; I've closed as a duplicate, but here are the collected fixes for your specific case:

Editing a file in-place with sed

With GNU sed:

sed -i 's/<libOld>/<libNew>/g' filename

with any sed:

sed 's/<libOld>/<libNew>/g' filename > filename.tmp && mv filename.tmp filename

Looping over a file line by line

for entry in names.txt only ever sets entry to names.txt, it doesn't read its contents. This is also BashFAQ/001.

while IFS= read -r entry; do
    printf '%s\n' "$entry"
done < names.txt

Looping over all files in a directory

You don't need a separate file, and you shouldn't use ls but globs:

for fname in ./*; do
    printf '%s\n' "$fname"
done

Combined for your case

Notice the double quotes around $entry.

for entry in ./*; do
    sed -i 's/<libOld>/<libNew>/g' "$entry"
done

which can be simplified to no loop at all:

sed -i 's/<libOld>/<libNew>/g' ./*
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116