Writing a word into every txt file in a folder

Solution 1:

A simple for will do the work:

for i in ./*.txt; do echo 'cat' >> "$i"; done;

This will get a list of all txt files in current directory, loops throughout them and echo cat into them (append to the content). you can change >> to >, to overwrite the files content with cat.

Another thing you can do is using tee to redirect a stream to multiple files.

To append:

echo "cat" | tee -a *.txt

To overwrite:

echo "cat" | tee *.txt

Solution 2:

If the files are not empty you can use sed without looping. To add cat at the start:

sed 'i\cat' *.txt

To add at the end:

sed 'a\cat' *.txt

To add after the second line:

sed '2 a\cat' *.txt

To add before lines with foo in them:

sed '/foo/ i\cat' *.txt

It doesn't work on empty files though. Kind of a bug.

(To actually write to the files after testing you need the -i option: sed -i 'a\cat' *.txt)

Solution 3:

Python approach:

#!/usr/bin/env python
import sys

for i in sys.argv[1:]:
    with open(i,'w') as fd:
        fd.write("cat\n")
  • it usessys module to iterate over command-line arguments
  • each command-line argument will be open as file for writing
  • "cat" with newline will be written to file before going to next

Usage would be as ./add_cat.py *.txt , which would operate on all .txt files in current working directory. Improvement to this could include using command-line argument #1 as string to write instead of hardcoding "cat" there.