10

How can I write the word "cat" into every .txt file in a folder?

20

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
| improve this answer | |
  • what is the con to use echo "cat" >> *.txt? – hytromo Apr 11 '17 at 22:19
  • 4
    @hakermania that should fail with ambiguous redirect – Zanna Apr 12 '17 at 4:35
13

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)

| improve this answer | |
  • I hate sed :)), cause theres a lot of things you can do with it and I'm not aware of them :)) – Ravexina Apr 11 '17 at 14:18
  • @Ravexina sed is my jam ;) – Zanna Apr 11 '17 at 14:18
  • why does 'i\cat' use the backslash instead of slash? – phuclv Apr 12 '17 at 11:27
  • @LưuVĩnhPhúc the backslash is optional actually, you can also put 'icat' or i cat. The backslash is conventional I believe. You can't use forwardslash - it will be literally inserted – Zanna Apr 12 '17 at 11:39
4

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.