开发者

Bash Script - Using Basename to Output to File

开发者 https://www.devze.com 2023-02-10 00:04 出处:网络
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开发者_如何学JAVA the

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开发者_如何学JAVA 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


Or the 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 should be using >> to append to the file instead of >.


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


Without calling basename:


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

精彩评论

暂无评论...
验证码 换一张
取 消