Home > Software design >  Get names of root directories in an array in bash
Get names of root directories in an array in bash

Time:05-20

I have a list of files which are stored here:

FILES_CHANGE=(git diff --name-only --cached)

This retrieves for example:

test.txt
home/a/c/test.sh
test/s.cpp

I need to get only the occurrencies with root directory name. In the example above would be:

home
test

How can I do this with bash? Any possibility to single line it with sed?

CodePudding user response:

Another option using :

git diff --name-only | cut -d '/' -f1

Local example:

$ git --no-pager diff --name-only
src/API/Api.php
src/Commands/Data/Data.php
$
$
$ git  diff --name-only | cut -d '/' -f1
src
src
$

CodePudding user response:

You can pipe to an awk to get desired output:

git ... | awk -F/ 'NF>1 {print $1}'

home
test

To populate an array in BASH 4 , use:

readarray -t ary < <(git ... | awk -F/ 'NF>1 {print $1}')

CodePudding user response:

The attraction of Awk is that you can also easily exclude duplicates.

git  diff --name-only | awk -F/ 'NF>1 && (!a[$1]  ) { print $1 }'

CodePudding user response:

Using sed

$ git  diff --name-only | sed -n 's|\(^[^/]*\)/.*|\1|p'
home
test
  • Related