Get one element of path string using bash
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.
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
You could do it directly in your read
command, using the IFS
variable e.g.
$ while IFS=/ read -r p1 p2 p3 r; do echo "$p2"; done < filelist.txt
first
second
third
You can use awk
pilot6@Pilot6:~$ cat filelist.txt
./first/example1/path
./second/example1/path
./third/example2/path
pilot6@Pilot6:~$ awk -F "/" '{print $2}' filelist.txt
first
second
third
pilot6@Pilot6:~$ awk -F "/" '{print $3}' filelist.txt
example1
example1
example2