[英]how to split a full file path into a path and a file name without an extension
如何將完整的文件路徑拆分為一個路徑和一個沒有擴展名的文件名? 我正在尋找擴展名為.conf 的任何文件: find /path -name .conf /path/file1.conf /path/smth/file2.conf /path/smth/file3.conf /path/smth/smth1/ 。 conf ... /path/smt/ /*.conf
我需要字符串中的輸出(不帶擴展名 .conf):/path;file1|path/smth;file2;file3|...
最好的方法是什么? 我正在考慮一個解決方案 - 將查找工作的輸出保存到一個文件中並在循環中處理它們......但也許有更有效的方法。 對不起,我是新手……謝謝你的反饋,伙計們!
既然你提到了.conf
,這有幫助嗎?
kent$ basename -s .conf '/path/smth/file2.conf'
file2
kent$ dirname '/path/smth/file2.conf'
/path/smth
要在 Bash 中執行此操作:
find /path/ -type f -name "*.conf"
請注意,如果您想在 Bash 腳本中執行此操作,您可以將 /path/ 存儲在一個變量中,例如一個命名目錄,並像這樣更改命令:
find $directory -type f -name "*.conf"
要在 Python 中執行此操作:
import os
PATH = /path/
test_files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(PATH) for f in filenames
if os.path.splitext(f)[1] == '.json']
還有一些其他方法可以在此處列出的 Python 中執行此操作
bash
參數解析簡單、快速且輕量級。
for fp in /path/file1.conf /path/smth/file2.conf /path/smth/file3.conf; do
p="${fp%/*}" # % strips the pattern from the end (minimal, non-greedy)
f="${fp##*/}" # ## strips the pattern from the beginning (max-match, greedy)
f="${f%.*}" # end-strip the already path-cleaned filename to remove extention
echo "$p, $f"
done
/path, file1
/path/smth, file2
/path/smth, file3
為了獲得您顯然想要的格式 -
declare -A paths # associative array
while read -r fp; do
p=${fp%/*} f=${fp##*/}; # preparse path and filename
paths[$p]="${paths[$p]};${f%.*}"; # p as key, stacked/delimited val
done < file
然后堆疊/分隔您的數據集。
for p in "${!paths[@]}"; do printf "%s|" "$p${paths[$p]}"; done; echo
/path;file1|/path/smth;file2;file3|
對於每個鍵,打印 key/val 和一個分隔符。 echo
在末尾換行。
如果您不想要尾管,請將其全部分配給第二個循環中的一個 var,而不是將其打印出來,並在最后修剪尾管。
$: for p in "${!paths[@]}"; do out="$out$p${paths[$p]}|"; done; echo "${out%|}"
/path;file1|/path/smth;file2;file3
有些人會告訴您不要將 bash 用於任何如此復雜的事情。 請注意,它可能會導致丑陋的維護,特別是如果在您身后維護它的人不是bash
專家並且不會費心去 RTFM。
如果您在示例中確實需要該嵌入空間,那么您的規則不一致,您必須對其進行解釋。
如果您在列表中有文件路徑,則可以使用帶有鍵路徑和值文件名的字典來執行此操作
aa=['/path/file1.conf','/path/smth/file2.conf','/path/smth/file3.conf']
f={}
for x in aa:
temp=x[:-len(".conf")].split("/")
filename=temp[-1]
path="/".join(temp[:-1])
if path in f:
f[path]=f[path]+","+filename
else:
f[path]=filename
result=""
for x in f:
result=result+str(x)+";"+f[x]+"|"
print(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.