Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file names from directory in Bash

Tags:

bash

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?

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.

like image 763
Leo.peis Avatar asked Jun 04 '12 12:06

Leo.peis


1 Answers

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.

like image 174
Charles Duffy Avatar answered Sep 30 '22 00:09

Charles Duffy