2

Here I have test.tar.gz file, it's structure like:

folder/
folder/folder1
folder/folder1/aa
folder/folder1/bb
folder/folder2
folder/folder2/cc

Is there a way to find the name of first-level folder?

Henry
  • 75
  • 1
  • 6

3 Answers3

8

For simple cases, what about:

tar tf archive.tar | head -1

... however tar archives are not necessary "single rooted":

sh$ mkdir -p folder/folder1
sh$ mkdir -p folder/folder2
sh$ touch folder/folder1/{aa,bb}
sh$ touch folder/folder2/cc
sh$ mkdir -p other/folder3
sh$ touch other/folder3/dd
sh$ mkdir -p yet/an/other
sh$ tar cvf f.tar folder other yet/an
folder/
folder/folder1/
folder/folder1/aa
folder/folder1/bb
folder/folder2/
folder/folder2/cc
other/
other/folder3/
other/folder3/dd
yet/an/
yet/an/other/

In addition, please note in the above example, the last entries: there is the sub-folder but not the root one.

In such case, you might extract the various "roots":

sh$ tar tf f.tar | sed -n '/^[^/]*\/$/p'
folder/
other/

If you need "unrooted" files too, this is more complicated:

sh$ $ tar tf f.tar | sed -n '/^.*\/$/p' | sort | cut -d '/' -f 1 | uniq
folder
other
yet

The sort is not strictly necessary in my example, but it helps if you have an incremental archive.

Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
  • 1
    It should probably be pointed out that sorting this way means no output will be generated until the entire tar archive has been scanned. – Etan Reisner Jul 23 '14 at 17:57
  • @EtanReisner Very correct. This might be an issue for very long archives and/or on very constrained hardware. – Sylvain Leroux Jul 23 '14 at 18:00
3

Using awk:

tar -tf bash-4.0.tar.gz | awk -F / 'NF > 1 && !a[$1]++ { print $1 FS }'

Output:

bash-4.0/
konsolebox
  • 72,135
  • 12
  • 99
  • 105
0

Yes! Take a look Here

tar tvf scripts.tar | awk -F/ '{if (NF<4) print }'


drwx------ glens/glens       0 2010-03-17 10:44 scripts/
-rwxr--r-- glens/www-data 1051 2009-07-27 10:42 scripts/my2cnf.pl
-rwxr--r-- glens/www-data  359 2009-08-14 00:01 scripts/pastebin.sh
-rwxr--r-- glens/www-data  566 2009-07-27 10:42 scripts/critic.pl
-rwxr-xr-x glens/glens     981 2009-12-16 09:39 scripts/wiki_sys.pl
-rwxr-xr-x glens/glens    3072 2009-07-28 10:25 scripts/blacklist_update.pl
-rwxr--r-- glens/www-data 18418 2009-07-27 10:42 scripts/sysinfo.pl

Make sure to note, that the number is 3+ however many levels you want, because of the / in the username/group. If you just do

tar tf scripts.tar | awk -F/ '{if (NF<3) print }'

scripts/
scripts/my2cnf.pl
scripts/pastebin.sh
scripts/critic.pl
scripts/wiki_sys.pl
scripts/blacklist_update.pl
scripts/sysinfo.pl

it's only two more.

Community
  • 1
  • 1
Bijan
  • 7,737
  • 18
  • 89
  • 149