0

I have the code:

for file in *
    do
      list="$list""$file "`cat $file | wc -l | sort -k1`$'\n'
   done

echo $list

This outputs a list like fileA 10 fileB 20 fileC 30.

I thought it should output:

fileA 10
fileB 20
fileC 30

I need the output to follow the latter as I then want to cycle through the $listvariable one line at a time and perform operations.

Could someone please help me out here?

Thank you.

  • Try `echo "$list"` instead. If you don't include the quotes the arguments will be split on whitespace and echo will separate them with a single space. – Gavin Smith Aug 12 '14 at 09:12
  • possible duplicate of [Trying to embed newline in a variable in bash](http://stackoverflow.com/questions/9139401/trying-to-embed-newline-in-a-variable-in-bash) – tripleee Aug 12 '14 at 10:28

2 Answers2

1

it does have the new-line characters in the variable. when a variable is used outside of quotes it splits it into multiple arguments separated by whitespace.

what you want is echo "$list"

programmerjake
  • 1,794
  • 11
  • 15
0

You can do it like this :

 for file in *
  do
     count=$(cat "$file" | wc -l)
     list="$list$file $count\n"
  done

echo -e $list

-e     enable interpretation of backslash escapes
bachN
  • 592
  • 3
  • 14