0

I have this project,

Parent
  |-ChildA
  |-ChildB
  |- ....
  |-ChildZ

and each child directory contains requirements.txt that has python package information like this,

packageA==0.1
packageB==5.9.3
...
packageZ==2.9.18.23

I want to cut off all version information so that output file will be,

packageA
packageB
...
packageZ

I am trying,

cat requirements.txt | grep "==" | cut -d "=" -f 1

but it does not iterate all subdirectories and does not save. How can I make it? Thanks!
*I am using ubuntu20.04

jayko03
  • 2,329
  • 7
  • 28
  • 51
  • [This one](https://stackoverflow.com/questions/6758963/find-and-replace-with-sed-in-directory-and-sub-directories) might help – Kosh Feb 05 '22 at 00:10

1 Answers1

1

In order to Execute the command on all the requirements.txt files, you'll need to iterate through all the Child directories, You can do so using this simple script:

#!/bin/sh

for child in ./Child* ; do
        cat "$child/requirements.txt" | grep "==" | cut -d "=" -f 1
done

Now if you wish to "save" the new version of each file, you can just redirect each command output to the file using the > operator. Using this operator will overwrite your file, so I suggest you redirect the output to a new file.

Heres the script with the redirected output:

#!/bin/sh

for child in ./Child* ; do
        cat "$child/requirements.txt" | grep "==" | cut -d "=" -f 1 > $child/cut-requirements.txt
done
  • 1
    This works, but [be careful when redirecting (`>`) output to the same file](https://stackoverflow.com/q/39426655/9157799), it will empty the existing files. [Use `sponge` instead](https://stackoverflow.com/a/6697219/9157799). – M Imam Pratama Feb 05 '22 at 00:47