如何将find的所有BASH结果输出到单个变量?更多详细信息发布



最新更新:

在Richard Jessop和他的评论的帮助下,我差点就想明白了。这是我目前的输出:

(
"DSC009.jpg"
"wallpaper.png"
"image732.bmp"
"animated.gif"
)

我只需要把最后一个换成),它应该很好!

//更新结束

关于:

我需要在所有子文件夹中搜索具有指定扩展名(.png、.jpg、gif、.bmp(的所有文件。然后,理想情况下,将所有结果的完整列表输出到单个变量中,如下例所示。结果区分大小写,必须用"双引号"括起来,并用转义符\分隔,如图所示。这将从bash脚本运行,而不是从shell提示符运行。

imagefiles=$(
"DSC009.jpg"
"wallpaper.png"
"image732.bmp"
"animated.gif")

我在这里和其他地方搜索了答案,并测试了我认为可能有效的代码,但所有尝试都失败了,任何帮助都将不胜感激。

所以代码应该是这样的:

var="$(此处插入代码(">

我尝试了很多解决方案和变体,但都没有成功,甚至只是得到了我想要的一些结果。正如有人所说,这里有一次这样的尝试失败了。同样,这些只是其中的一些变体。我尝试过不带引号、带引号、单引号等($path不包含空格(。

imagefiles="find $path -type f -name ".(png|jpg|gif|bmp)" -printf '%fn'"
imagefiles=$("find $path -type f -name ".(png|jpg|gif|bmp)""
imagefiles="$(find '$path' -type f ( -iname *.jpg -o -iname *.png ))"
imagefiles="$(find $path -type f *.png)"

同样,以上任何一种方法都不能以最简单的方式工作,只能返回一个结果。

编辑:为了进一步澄清,这里有另一个简单的例子:

#!/bin/bash
#ROOT PATH OF FOLDERS CONTAINING IMAGES
path="/media/backup/photos/"
#FIND ALL IMAGE TYPES
imagefiles="$(find $path -type f '.(png|jpg|gif|bmp)')"
#REMOVE IMAGE PATHS
list=`basename "$imagefiles"`
#CHECK TO VERIFY/DEBUG OUTPUT
echo "$list" > /media/found.txt
#FOUND.TXT SHOULD LOOK LIKE:
#DSC009.jpg
#wallpaper.png
#image732.bmp
#animated.gif
#CREATE NEW VARIABLE BUT SOMEHOW OUTPUT LIKE EXAMPLE BELOW
images="$(cat found.txt)"
#EXAMPLE:
#(
#"DSC009.jpg"
#"wallpaper.png"
#"image732.bmp"
#"animated.gif")

希望这能让事情好转一点。

这里有一个部分解决方案:

for file in $(find . -mindepth 1 | egrep '.(png|txt)$')
do
echo -e "   "$file"\"
done

mindepth选项跳过当前目录。我试着把白鹭移到有这个选择的地方,但我无法让它发挥作用。

这将使您的多个缩进行以\结尾。希望你或其他人能够填写其余的细节。

您可以使用find -printf以您想要的方式输出每个结果。使用sed:可以很容易地完成最后一个元素的标头和修改

myvar="$(
find "${path?}" ( -name '*.png' -o -name '*.jpg' )  -printf '"%f"\n' |
sed -e '1i(\' -e '$s,\$,),'
)"

这使用1i在第1行指定插入,使用$s在最后一行进行替换,特别是使用)的尾部

如果你需要它更符合POSIX,你可以做:

myvar="$(
printf '%sn' '('
find "${path?}" -name '*.png' -o -name '*.jpg' |
sed -e 's,(.*/)*(.*),"2"\,' -e '$s,\$,),'
)"

特别感谢@Richard Jessop&另一个人的帖子帮助我指明了正确的方向。以及其他任何花时间和精力发表评论的人

我知道这里提到的ls解析是禁忌,但在我的情况下,它可以按预期工作,而且很容易设置。

如果你知道有更好的方法可以达到同样的效果,那么请尽一切努力与他人分享。请记住,在我的情况下,-printf不可用。

这是我想要的工作解决方案!

#!/bin/bash
imagePath="/media/photos/"
#Remove the previous results before beginning
rm -f /media/images.txt
#List all images found with matching extensions and output only the filenames to images.txt file.
for images in $(ls -a -R $imagePath | egrep '.JPG$|.jpg$|.png$|.PNG$')
do
#Output filenames like so "IMAGENAME.EXT"
echo -e "   "$images"\" >> /media/images.txt
done
#'1i (\' Starts the file with ( and '$s,\$,),' substitutes the final  with a ).  
sed -i -e '1i (\' -e '$s,\$,),' /media/images.txt
#Creates a Variable from the output in the images.txt file.
myVar=$(cat /media/images.txt)
#See, it works!
echo "$myVar"

最新更新