Home > OS >  How can I cut off tail of each line in the text file in all subfolders with shell script?
How can I cut off tail of each line in the text file in all subfolders with shell script?

Time:02-08

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

CodePudding user response:

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
  •  Tags:  
  • Related