如何将带有换行符的字符串从函数传递到数组? [英] How to pass strings with newlines from function to array?

查看:247
本文介绍了如何将带有换行符的字符串从函数传递到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Bash我正在从二进制文件中提取多个字符串。这些字符串是文件名,因此只能显示NUL和斜杠。我使用了将这些文件名输出到数组的函数。我知道,我可以使用IFS分隔符换行符来获取带空格的文件名。我希望可以将函数多行字符串与NUL分开以保存在数组中,以便可以使用任何* nix合法文件名。如果我将IFS设置为或 0,则会得到一些数字而不是名称。不知道为什么,也许我已经监督了一些非常基本的东西:)
如何获得所有可能的文件名字符串,不仅包括空格,还包括换行符和其他字符/字节值?

Using Bash I am extracting multiple strings from a binary file. Those strings are filenames, so only NUL and slash can not appear. I use a function that outputs those filenames to an array. I know, I can use IFS separator newline to get filenames with spaces. I hope it is possible to separate functions multiline strings with NUL to save in array, so any *nix legal filename can be worked with. If I set IFS to '' or '\0' I get some numbers instead of names. Not sure why, and maybe I have overseen something pretty basic :) How do I achieve getting all possible filename strings including not just spaces, but newlines and other characters/byte values as well?

这是我的简化示例。

#! /bin/bash
binaryFile=$1

getBinaryList () {
    fileNameAddresses=( 123 456 789 )           #Just a mock example for simplicity
    for currAddr in "${fileNameAddresses[@]}"
    do
        fileNameStart=$((currAddr))             #Just a mock example for simplicity
        fileNameLength=48                       #Just a mock example for simplicity
        currFileName=$( dd status=none bs=1 skip=$fileNameStart count=$fileNameLength if=$binaryFile )
    printf "%s\n" "$currFileName"
    done
}

IFS=$'\n'
allFileNames=($(getBinaryList $binaryFile))

echo ${#allFileNames[@]}
printf "%s\n" "${allFileNames[@]}"


推荐答案

您的想法是正确的,但是只需进行一些细微修改,即可实现所需的功能。在 getBinaryList()函数中,而不是使用 printf()以换行格式输出输出,请使用NULL字节分隔符,即

Your idea is right, but with a couple of slight modifications you can achieve what you are looking for. In the getBinaryList() function instead of using printf() emitting output with newline formatting, use a NULL byte separator, i.e.

printf "%s\0" "$currFileName"

,而不是将 IFS 修改为换行符,然后将结果插入数组。使用类似 mapfile 的命令将结果直接放入数组。该命令提供了一个选项,用 -d''在NULL字节上定界并将结果存储在 -t 。因此您的结果看起来像是

and now instead of modifying IFS to newline and slurping the result into an array. Use a command like mapfile which puts the results directly into array. The command provides an option to delimit results on the NULL byte with -d '' and to store in array specified by -t. So your result can look like

mapfile -t -d '' allFileNames < <(getBinaryList "$binaryFile")

这篇关于如何将带有换行符的字符串从函数传递到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆