1

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.

R. Davis
  • 11
  • 4

2 Answers2

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 )"
muru
  • 72,889
icarus
  • 17,920
  • 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.

  • Would you want to get all .txt files recursively, it would be far better to do list=( ./**/*.txt ) with the globstar option 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
    See https://unix.stackexchange.com/questions/321697 – Kusalananda Apr 07 '20 at 17:07
  • @Kusalananda thanks for info. I will check it – user3417815 Apr 07 '20 at 17:08