从Bash中的目录中读取文件名 [英] Read file names from directory in Bash

查看:68
本文介绍了从Bash中的目录中读取文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个脚本,该脚本从目录中读取所有文件名,然后根据文件名(例如,如果它包含R1或R2),它将所有包含该文件名的文件(例如,R1)串联在一起.名称.

I need to write a script that reads all the file names from a directory and then depending on the file name, for example if it contains R1 or R2, it will concatenates all the file names that contain, for example R1 in the name.

任何人都可以给我一些提示,怎么做?

Can anyone give me some tip how to do this?

我唯一能做的是:

#!/bin/bash

FILES="path to the files"

for f in $FILES
do
  cat $f
done

这只告诉我变量FILE是一个目录,而不是它具有的文件.

and this only shows me that the variable FILE is a directory not the files it has.

推荐答案

进行最小的更改以解决问题:

To make the smallest change that fixes the problem:

dir="path to the files"
for f in "$dir"/*; do
  cat "$f"
done

要完成您描述为所需的最终目标:

To accomplish what you describe as your desired end goal:

shopt -s nullglob
dir="path to the files"
substrings=( R1 R2 )
for substring in "${substrings[@]}"; do
  cat /dev/null "$dir"/*"$substring"* >"${substring}.out"
done

请注意,cat可以在一次调用中获取多个文件-实际上,如果您不这样做,则通常根本不需要使用cat.

Note that cat can take multiple files in one invocation -- in fact, if you aren't doing that, you usually don't need to use cat at all.

这篇关于从Bash中的目录中读取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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