简体   繁体   English

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

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

I would like to remove a file name only from the following configuration file. 我只想从以下配置文件中删除文件名。

Configuration File -- test.conf 配置文件 -test.conf

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

The above file should be read. 上面的文件应该阅读。 And removed contents should went to another file called output.txt 删除的内容应转到另一个名为output.txt的文件

Following are my try. 以下是我的尝试。 It is not working to me at all. 它根本对我不起作用。 I am getting empty files only. 我只得到空文件。

#!/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"

Expected Output : 预期产量:

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

There's the dirname command to make it easy and reliable: dirname命令可以使它变得简单可靠:

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

There are Bash shell parameter expansions that will work OK with the list of names given but won't work reliably for some names: 有Bash shell参数扩展可以与给定的名称列表一起使用,但对于某些名称将无法可靠地运行:

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

There's sed to do the job — easily with the given set of names: sed可以完成这项工作-轻松使用给定的名称集:

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

It's harder if you have to deal with names like /plain.file (or plain.file — the same sorts of edge cases that trip up the shell expansion). 如果必须处理类似/plain.file (或plain.file -导致shell扩展plain.file的边缘情况)之类的名称,这将变得更加困难。

You could add Perl, Python, Awk variants to the list of ways of doing the job. 您可以将Perl,Python,Awk变体添加到完成工作的方式列表中。

Using awk one liner you can do this: 使用awk one班轮,您可以执行以下操作:

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

Output: 输出:

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

You can get the path like this: 您可以这样获得路径:

  path=${fullpath%/*}

It cuts away the string after the last / 它在最后一个/之后切掉字符串

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

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