0
votes

I'm trying to add a string to the beginning of many files, creating a new file extension whilst maintaining the filename.

cat string.txt file001.old > file001.new
cat string.txt file002.old > file002.new
cat string.txt file003.old > file003.new
etc...

I tried to batch it by:

for i in *.old
do
    cat string.txt $i > $i.new
done

But this didnt exactly work, my skills are limited... Thanks in advance for any help.

3
What is not working? Is string.txt a file (if not, you need to echo the string). Or do you have new files with names like file002.old.new ? Or do you have filenames with spaces that get mixed up?Walter A

3 Answers

0
votes

Or this shorter alternative

for i in *.old
do
  echo string.txt | cat - $i > ${i%old}new
done

or even with heredoc instead of pipe

for i in *.old
do
  cat - $i <<< string.txt > ${i%old}new
done
0
votes

There are several ways to do it. This may be the simplest:

for i in *.old
do
  echo string.txt > ${i%old}new
  cat $i >> ${i%old}new
done
0
votes

Thanks guys... I forgot to add the punctuation marks, Should look something like this:

for i in *.old
do
    cat string.txt "$i" > "$i".new
done

The output would look like "file002.old.new" Where I used SED to remove the old extention But I will definitely be trying the alternate methods

Thanks again, Nem