Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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
like image 237
ArunRaj Avatar asked Oct 30 '25 09:10

ArunRaj


2 Answers

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.

like image 113
Jonathan Leffler Avatar answered Nov 01 '25 23:11

Jonathan Leffler


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
like image 29
anubhava Avatar answered Nov 02 '25 01:11

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!