Bash 脚本 - 使用 Basename 输出到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4961373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:26:22  来源:igfitidea点击:

Bash Script - Using Basename to Output to File

bashunix

提问by muttley91

I've created a small script to test out getting the basename of all files in the current directory. I want to output them all to a file output.txtbut using a for loop, of course the file is just overwritten each time. Using the following code, how could I modify it to simply append each one to the end of the file (simply)?

我创建了一个小脚本来测试获取当前目录中所有文件的基本名称。我想将它们全部输出到一个文件中,output.txt但使用 for 循环,当然该文件每次都会被覆盖。使用以下代码,我如何修改它以简单地将每个附加到文件的末尾(简单地)?

#!/bin/bash

files=$(find -size +100)

for f in $files; do
    basename "$f" > output.txt
done

exit

回答by Glen Solsberry

Or the oneliner:

或者单线:

find -size +100 -exec basename "{}" \; >> output

回答by Paused until further notice.

Use MrAfs' suggestion and move the redirection to the end of the loop. By using >instead of >>you don't have to truncate the file explicitly.

使用 MrAfs 的建议并将重定向移动到循环的末尾。通过使用>而不是>>您不必显式截断文件。

Also, use a while readloop so it works in case there are spaces in filenames. The exitat the end is redundant.

此外,使用while read循环,以便在文件名中有空格的情况下工作。所述exit在端部是多余的。

#!/bin/bash

find -size +100 | while read -r f
do
    basename "$f"
done > output.txt

In some cases, you will want to avoid creating a subshell. You can use process substitution:

在某些情况下,您会希望避免创建子 shell。您可以使用进程替换:

#!/bin/bash

while read -r f
do
    basename "$f"
done < <(find -size +100) > output.txt

or in the upcoming Bash 4.2:

或者在即将发布的 Bash 4.2 中:

#!/bin/bash

shopt -s lastpipe    
find -size +100 | while read -r f
do
    basename "$f"
done > output.txt

回答by Mark Loeser

You should be using >>to append to the file instead of >.

您应该使用>>附加到文件而不是>.

回答by MrAfs

You can redirect bash constructs

您可以重定向 bash 结构

#!/bin/bash

files=$(find -size +100)

for f in $files; do
    basename "$f" 
done > output.txt

exit

回答by Alex Howansky

You can do this:

你可以这样做:

rm -f output.txt
for f in $files; do
    basename "$f" >> output.txt
done

Or this:

或这个:

for f in $files; do
    basename "$f"
done > output.txt

回答by hipe

Without calling basename:

不调用基名:


find -size +100 -printf "%f\n" > output.txt