C
C
Chuck Thornton2019-11-01 14:43:30
bash
Chuck Thornton, 2019-11-01 14:43:30

Recursively iterating over files in folders and subfolders and putting their contents into a single text file?

Hello.
I have recently been working with Bash, so do not kick hard) The
question is this.
There was a need to recursively go through all the subfolders of the directory and put the contents of all files into one, indicating the current location and name.
So far, it turns out to collect the contents of the files in the current folder and place them in a text box, with the following script:

cd /home/myUser/Documents/repos/core/

for f in * ; do echo -E -- "$f" -- && pwd && cat -- "$f" ; done >> name.txt

But here's how to go through other subfolders recursively and put the contents of their files into the same file.. it doesn't work.
I roughly understand that you can use for or somehow find to apply.
I would be grateful for advice and help)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Chuck Thornton, 2019-11-01
@ctornton

As a result, he solved his own question, as he expected, using find.
Below is the code, suddenly someone will come in handy in the future, who will have a similar question.

#!/usr/bin/env bash

for file in `find /path/to/your/directory/ -type f -name "*"`
do
   echo -E -- ${file} -- && cat -- ${file} ;
done > /path_to_your_new_file/nameFile.txt

This is how the script runs through all the folders and subfolders of the directory specified at the very beginning, takes their contents and puts them in the file specified at the end, in the .txt format.
Oh yes, when he finishes listing the contents of one file in our new text file, he points to the path to the next one and its name.

V
Viktor Taran, 2019-11-01
@shambler81

it's not entirely clear what you want
, you need to combine "all contents" do I understand correctly that the question is about the files contained in the directories? i.e. all files are found in the given directory and below should be detached ?
If so then here
If you just need to merge all files and directories into one file with the ability to restore directories, then tar can do it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question