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
: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:You could do it directly in your
read
command, using theIFS
variable e.g.You can use
awk
If we want any element of the path, it is best to use something that can break up a string into fields, such as awk, cut ,python, or perl. However, bash can also do the job with parameter substitution,using pattern replacement and throwing everything into an array.
Now we have an array of items made out of the path. Note that if the path contains spaces, it may involve altering internal field separator
IFS
.Bash and
cut
are the way to go, however an alternative using Perl:for the second
/
-delimited field andfor the third
/
-delimited field.-l
: enables automatic line-ending processing. It has two separate effects. First, it automatically chomps $/ (the input record separator) when used with -n or -p. Second, it assigns $\ (the output record separator) to have the value of octnum so that any print statements will have that separator added back on. If octnum is omitted, sets $\ to the current value of $/.-a
: turns on autosplit mode when used with a -n or -p. An implicit split command to the @F array is done as the first thing inside the implicit while loop produced by the -n or -p.-n
: causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:-e
: may be used to enter one line of program;print(@F[N])
: prints the Nth field.