[英]Bash Script - Using Basename to Output to File
我創建了一個小腳本來測試獲取當前目錄中所有文件的基本名稱。 我想將它們全部輸出到文件output.txt
但是使用for循環,當然每次都只是覆蓋該文件。 使用以下代碼,我如何修改它以將每個簡單地附加到文件末尾(簡單地)?
#!/bin/bash
files=$(find -size +100)
for f in $files; do
basename "$f" > output.txt
done
exit
或oneliner:
find -size +100 -exec basename "{}" \; >> output
使用MrAfs的建議並將重定向重定向到循環的結尾。 通過使用>
而不是>>
您不必顯式截斷文件。
另外,請使用while read
循環,以防文件名中包含空格。 最后的exit
是多余的。
#!/bin/bash
find -size +100 | while read -r f
do
basename "$f"
done > output.txt
在某些情況下,您將希望避免創建子外殼。 您可以使用流程替換:
#!/bin/bash
while read -r f
do
basename "$f"
done < <(find -size +100) > output.txt
或即將發布的Bash 4.2中:
#!/bin/bash
shopt -s lastpipe
find -size +100 | while read -r f
do
basename "$f"
done > output.txt
您應該使用>>
而不是>
附加到文件。
您可以重定向bash結構
#!/bin/bash
files=$(find -size +100)
for f in $files; do
basename "$f"
done > output.txt
exit
你可以這樣做:
rm -f output.txt
for f in $files; do
basename "$f" >> output.txt
done
或這個:
for f in $files; do
basename "$f"
done > output.txt
不調用基本名:
find -size +100 -printf "%f\n" > output.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.