Ubuntu – Get one element of path string using bash

bashcommand linetext processing

I have an ASCII file containing filepaths which I read by running:

while read p; do echo $p; done < filelist.txt

The file contains filepaths with the following pattern:

./first/example1/path
./second/example1/path
./third/example2/path

How can I get a specific part of the path string (from / to / ), e.g.
I need to get an output that prints:

first
second
third

and also

example1
example1
example2

I'm sure there is a way of doing this using regular expressions and sed, but I'm not familiar with it.

Best Answer

Use cut:

$ cat filelist.txt
./first/example1/path
./second/example1/path
./third/example2/path

$ cut -d/ -f2 filelist.txt 
first
second
third

$ cut -d/ -f3 filelist.txt 
example1
example1
example2

The -d/ sets the column delimiter to / and the -f2 selects the 2nd column.

You can of course also use Bash variables instead of a file name or pipe data into the cut command:

cut -d/ -f3 $MyVariable
echo ./another/example/path | cut -d/ -f3