0

I need to output an array to a file in the following format.

File: a.txt
      b.txt

I tried doing the following :

declare -a files=("a.txt" "b.txt")
empty=""
printf "File:" >> files.txt
for i in "${files[@]}"
do 
   printf "%-7s %-30s \n" "$empty" "$i" >> files.txt
done 

But, I get the output as

 File: a.txt
 b.txt

Can anyone please help me to get the output in the required format.

3 Answers 3

1
#!/bin/bash

files=( 'a.txt' 'b.txt' 'c.txt' 'd.txt' )

set -- "${files[@]}"

printf 'File: %s\n' "$1"
shift
printf '      %s\n' "$@"

Output:

File: a.txt
      b.txt
      c.txt
      d.txt

This uses the fact that printf will reuse its formatting string for all its other command line parameters.

We set the positional parameters to the list and then output the first element with the File: string prepended. We then shift $1 off the list of positional parameters and print the rest with a spacer string inserted.

Sign up to request clarification or add additional context in comments.

Comments

0

Using sed

#!/bin/bash

declare -a files=("a.txt" "b.txt")

for i in "${files[@]}"
do
   echo "$i" >> files.txt
done
sed -i '1 s/^/File: /' files.txt
sed -i '1 ! s/^/      /' files.txt

If you are using Mac, you have to modify sed commands in this way

sed -i '' '1 s/^/File: /' files.txt
sed -i '' '1 ! s/^/      /' files.txt

The output will be:

File: a.txt
      b.txt

First of all we put into txt file all the file names (for loop). After that, via first sed command we add File: to the first line and via second sed command we add to all lines, except the first, six spaces equal to length of string File:

Comments

0

You could always started with a variable containing File: for the first iteration, and overwrite it with the correct number of spaces each time. The repeated assignment won't induce too much overhead.

prefix="File:"

for i in "${files[@]}"
do 
   printf "%-7s %-30s \n" "$prefix" "$i"
   prefix=
done > Files.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.