2

I am trying to print names of all .txt files from current folder in one line. I am using following script. However, it is not printing file names.

REF_SEQ=""
find . -name "*.txt" -maxdepth 1 -type f |
while read f;
do
    name=$(echo ${f}| xargs -I {} basename {} )
    REF_SEQ+="${name} "
done

echo "Full Sequence:  ${REF_SEQ}"

I have 3-4 .txt files in my current folder (A.txt, B.txt ...). I am expecting output as

Full Sequence: A.txt B.txt ...

If I just use find command without assigning output to variable RED_SEQ, I do get desired output. This suggests that find command is working fine but somehow I am unable to assign it to variable. I tried various different assignment operators but still no luck.

1

To update a variable in bash, you must use this syntax:

VAR="some stuff$VAR"

But, since you are using a pipe, the while loop is executed in a sub-shell, you variable is lost.

To correct this, you must have the syntax:

while read f
do
done <<< $(input)

So in your case:

REF_SEQ=""

while read f;
do
    name=$(echo ${f}| xargs -I {} basename {} )
    REF_SEQ="${REF_SEQ}${name} "
done <<< $(find . -name "*.txt" -maxdepth 1 -type f)

echo "Full Sequence:  ${REF_SEQ}"
  • Unfortunately, this doesn't work. I have tried it already. – UserOnWeb Jun 4 '19 at 14:25
  • @DexOnWeb yes I answer too fast, corrected – Mathieu Jun 4 '19 at 14:33
  • Thank you. It worked :) – UserOnWeb Jun 4 '19 at 14:36
0

The problem is, that you use {} behind the pipe symbol. This is just valid in the -exec option of find, but not behind the pipe symbol.

You could try the following:

REF_SEQ=$(find . -maxdepth 1 -name "*.txt" -type f -printf "%f " | xargs)

This should produce the result you desire. The printf-directive %f outputs the basename of the file found and the xargs "transposes" the result.

Kind regards Jürgen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.