Issue
I try to add a string to the first line in text files.
The first part of every string is identical. Here "#Test:". The last part of the string should incorporate the digit which is derived from the folder and file names. The folder names consist exclusively of digits from 1-52. There are between 1-20 files in each folder with the following structure:
1 (folder)
1_tree1 (file)
1_tree2 (file)
1_tree3 (file)
...
2 (folder)
2_tree1 (file)
2_tree2 (file)
2_tree3 (file)
...
...
The operating system is Ubuntu 20.04.
I am able to change each file separately. For example, the following command in the terminal adds #Tree:1 for one file the first folder.
sed -i '1s/^/#Test:1 \n/' '/path/to/the/file'
However, if I try to do this for all files in the folder, I can not proceed. Could you show me how to do it automatically? I am not necessarily restricted to sed
.
Thank you.
Solution
This might be what you want, using GNU awk for "inplace" editing, BEGINFILE
(so it'll work even on empty input files), and gensub()
:
find . -type f -exec awk -i inplace '
BEGINFILE { print "#Test:" gensub(".*/([0-9]+)_[^/]+$","\\1",1,FILENAME) }
1' {} +
Answered By - Ed Morton Answer Checked By - Mary Flores (WPSolving Volunteer)