数组中的Grep输出线

MNe*_*hev 3 linux bash grep

我试图将我的grep输出行作为元素放入数组中。

grep之后的输出(例如,文件存储在/ asd文件夹中)

test.mp4
test2.mp4
Run Code Online (Sandbox Code Playgroud)

所以这是最后的方式:

arr_name[0] = test.mp4
arr_name[1] = test2.mp4
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我的代码:

arr_name=( $(cd ~/asd; ls -tr | grep -v total | head -2) )
Run Code Online (Sandbox Code Playgroud)

您能帮我解决错误吗?

anu*_*ava 5

您不需要grep此处,可以避免ls使用-I选项解析输出ls

# To list all files except *total*
ls -I '*total*' -tr

# to read all the listed entries in an array
mapfile -t  arr < <(ls -I '*total*' -tr)

# to get first 2 entries
echo "${arr[@]:0:2}"

# to store 2 entries in an array
parr=("${arr[@]:0:2}")

# check your results
declare -p parr
Run Code Online (Sandbox Code Playgroud)