Muzik
Muzik

Reputation: 33

Reading the contents of a text file and assign to a variable using bash script

I want to read the contents of a text file and check for the filenames with extension .txt and find merge those .txt files.Is there a way I could do this using bash? For example, if the text file contains, file1.txt, file2.txt I want to read the strings with .txt extension and find merge those files which is in another location.

I tried the below,

txt_file="/tmp/Muzi/tomerge.txt"
while read -r line;do
    echo $line
done <"$txt_file"

But, this prints out the complete text file and I am completely new using bash.

Upvotes: 1

Views: 76

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9664

There is a good deal of assuming involved, but... if I understood your question, you would have a tomerge.txt where on some lines a filename would appear, one per line, ending in .txt. If that is the case (and the filenames do not contain spaces) you can:

cat $(grep '[.]txt$' tomerge.txt)

It's not bash only (uses cat), it concatenates files corresponding to all lines ending in .txt we've collected from tomerge.txt.

Upvotes: 1

Related Questions