从 Bash 目录中读取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10881157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read file names from directory in Bash
提问by Leo.peis
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.
我需要编写一个脚本,从目录中读取所有文件名,然后根据文件名,例如,如果它包含 R1 或 R2,它将连接所有包含名称的文件名,例如 R1。
Can anyone give me some tip how to do this?
谁能给我一些提示如何做到这一点?
The only thing I was able to do is:
我唯一能做的就是:
#!/bin/bash
FILES="path to the files"
for f in $FILES
do
cat $f
done
and this only shows me that the variable FILE is a directory not the files it has.
这仅向我表明变量 FILE 是一个目录,而不是它拥有的文件。
回答by Charles Duffy
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
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.
请注意,cat
可以在一次调用中获取多个文件——事实上,如果您不这样做,通常根本不需要使用 cat。
回答by Bubba
Simple hack:
简单的黑客:
ls -al R1| awk '{print $9}' >outputfilenameR1
ls -al R2| awk '{print $9}' >outputfilenameR2
ls -al R1| awk '{print $9}' >outputfilenameR1
ls -al R2| awk '{print $9}' >outputfilenameR2