I have a directory with almost 400 files and I want to assign all of the .txt files to a single variable in a bash script i'm writing. However i'm not terribly sure how to do that. I'm purely interested in the filenames themselves, not the content of said files.
Asked
Active
Viewed 1,564 times
1
-
The names of the files or the contents of the files? – icarus Apr 07 '20 at 02:46
2 Answers
1
If you want the names, you will probably be best off assigning them to an array.
names=( *.txt )
If you want the contents then
contents="$( cat *.txt )"
-
So currently, I have the following: #!/bin/bash dir =(*.txt) echo dir
I get an error when i run my script that '(' is an unexpected token.
– R. Davis Apr 07 '20 at 03:01 -
1@R.Davis make sure there is no space around the equals sign:
dir=( *.txt )– guest Apr 07 '20 at 04:21
-1
Do something like this. This one-liner produces an array for all .txt files in /root/tmpdir folder:
[root@localhost ~]# export LIST=() ; for file in `find /root/tmpdir -name *.txt -exec readlink -e '{}' \;` ; do LIST+=($file) ; done
[root@localhost ~]# echo ${LIST[*]}
/root/tmpdir/newdir/file.txt /root/tmpdir/file.txt
[root@localhost ~]#
Or, you can just create a variable containing filenames separated by ,:
[root@localhost ~]# export LIST; for file in `find /root/tmpdir -name *.txt -exec readlink -e '{}' \;` ; do LIST=$LIST$file, ; done
[root@localhost ~]# echo $LIST
/root/tmpdir/newdir/file.txt,/root/tmpdir/file.txt,
P.S.
Both examples look for file extension .txt not content. Plus, this find is recursive one, you can change the arguments to make it search within one folder only.
user3417815
- 268
-
Would you want to get all
.txtfiles recursively, it would be far better to dolist=( ./**/*.txt )with theglobstaroption set. Your approach would split filenames on whitespaces (and the second approach also disqualifies names that have commas). – Kusalananda Apr 07 '20 at 05:38 -
@Kusalananda fair point for the second option, but I don't see anything bad for the first one. There is nothing particular for this about the task itself, nor it's competition. I don't see a reason for downvote at all. – user3417815 Apr 07 '20 at 16:51
-
1
-