简体   繁体   中英

Bash Script - Using Basename to Output to File

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.txt but 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)?

#!/bin/bash

files=$(find -size +100)

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

exit

或oneliner:

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

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.

Also, use a while read loop so it works in case there are spaces in filenames. The exit at the end is redundant.

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

#!/bin/bash

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

or in the upcoming Bash 4.2:

#!/bin/bash

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

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

You can redirect bash constructs

#!/bin/bash

files=$(find -size +100)

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

exit

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

不调用基本名:


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

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