繁体   English   中英

如何从Shell中的路径列表中删除文件名

[英]How to remove a filename from the list of path in Shell

我只想从以下配置文件中删除文件名。

配置文件 -test.conf

knowledgebase/arun/test.rf
knowledgebase/arunraj/tester/test.drl
knowledgebase/arunraj2/arun/test/tester.drl

上面的文件应该阅读。 删除的内容应转到另一个名为output.txt的文件

以下是我的尝试。 它根本对我不起作用。 我只得到空文件。

#!/bin/bash
file=test.conf
while IFS= read -r line
do
#       grep --exclude=*.drl line
#       awk 'BEGIN {getline line ; gsub("*.drl","", line) ; print line}'
#       awk '{ gsub("/",".drl",$NF); print line }' arun.conf
#       awk 'NF{NF--};1' line arun.conf
echo $line | rev | cut -d'/' -f 1 | rev >> output.txt
done < "$file"

预期产量:

knowledgebase/arun
knowledgebase/arunraj/tester
knowledgebase/arunraj2/arun/test

dirname命令可以使它变得简单可靠:

#!/bin/bash
file=test.conf
while IFS= read -r line
do
    dirname "$line"
done < "$file" > output.txt

有Bash shell参数扩展可以与给定的名称列表一起使用,但对于某些名称将无法可靠地运行:

file=test.conf
while IFS= read -r line
do
    echo "${line%/*}"
done < "$file" > output.txt

sed可以完成这项工作-轻松使用给定的名称集:

sed 's%/[^/]*$%%' test.conf > output.txt

如果必须处理类似/plain.file (或plain.file -导致shell扩展plain.file的边缘情况)之类的名称,这将变得更加困难。

您可以将Perl,Python,Awk变体添加到完成工作的方式列表中。

使用awk one班轮,您可以执行以下操作:

awk 'BEGIN{FS=OFS="/"} {NF--} 1' test.conf

输出:

knowledgebase/arun
knowledgebase/arunraj/tester
knowledgebase/arunraj2/arun/test

您可以这样获得路径:

  path=${fullpath%/*}

它在最后一个/之后切掉字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM