简体   繁体   中英

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

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

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:

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

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 '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).

You could add Perl, Python, Awk variants to the list of ways of doing the job.

Using awk one liner you can do this:

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 /

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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