使用 bash 获取路径字符串的一个元素

mcE*_*nge 10 command-line bash text-processing

我有一个 ASCII 文件,其中包含我通过运行读取的文件路径:

while read p; do echo $p; done < filelist.txt
Run Code Online (Sandbox Code Playgroud)

该文件包含具有以下模式的文件路径:

./first/example1/path
./second/example1/path
./third/example2/path
Run Code Online (Sandbox Code Playgroud)

如何获取路径字符串的特定部分(从//),例如我需要获取打印的输出:

first
second
third
Run Code Online (Sandbox Code Playgroud)

并且

example1
example1
example2
Run Code Online (Sandbox Code Playgroud)

我确信有一种方法可以使用正则表达式 and 来做到这一点sed,但我不熟悉它。

Byt*_*der 18

使用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
Run Code Online (Sandbox Code Playgroud)

-d/设置列分隔符/-f2选择第2列。

您当然也可以使用 Bash 变量而不是文件名或管道数据到cut命令中:

cut -d/ -f3 $MyVariable
echo ./another/example/path | cut -d/ -f3
Run Code Online (Sandbox Code Playgroud)

  • @mcExchange 没有理由使用那个 while 循环。只执行 `cut -d/ -f3 filelist.txt` 要简单得多 (3认同)

ste*_*ver 10

你可以直接在你的read命令中使用IFS变量例如

$ while IFS=/ read -r p1 p2 p3 r; do echo "$p2"; done < filelist.txt 
first
second
third
Run Code Online (Sandbox Code Playgroud)


Pil*_*ot6 5

您可以使用 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
Run Code Online (Sandbox Code Playgroud)