Unix Shell Programming: Add a blank line when prin

2019-03-04 12:48发布

I am trying to list all the files in the directory but how would you separate each of the files by a blank line? basically each file displayed by separated by a blank line? I am trying to use a for loop? I did try few examples but none really work by spacing a blank lines in between?

for i in ls  
do
echo "\n" && ls -l
done

for i in ls  
do
echo "\n" 
ls 
done

5条回答
对你真心纯属浪费
2楼-- · 2019-03-04 13:32

For reference : http://www.cyberciti.biz/faq/bash-loop-over-file/

for f in /tmp/play/*
do
  echo $f
  echo
done

Edited as per comments making it simpler.

查看更多
ら.Afraid
3楼-- · 2019-03-04 13:32

sed one-liner (or one-char-er):

ls | sed G

Done.

查看更多
倾城 Initia
4楼-- · 2019-03-04 13:33

Here's one:

find -printf '%p\n\n'

A slightly worse (but more portable) one:

ls | sed 's|$|\n|'

A more convoluted one:

ls | while read f; do
    echo "$f"
    echo
done

And here is what you should not ever do:

for f in `ls`; do
    echo "$f"
    echo
done

EDIT:

And, as mentioned by Nija, the simple shell-only one:

for f in *; do
    echo "$f"
    echo
done

This one has the disadvantage that on many shells * by default expands to itself, rather than an empty string when no files exist.

查看更多
forever°为你锁心
5楼-- · 2019-03-04 13:48

Your loops are close. However, using a traditional bash for loop with ls is dangerous - what happens if your filenames contain spaces? An easy solution with awk:

ls | awk '{ print $0 "\n" }'
查看更多
贪生不怕死
6楼-- · 2019-03-04 13:48

Not sure how portable the options -d and -t are, but pr is ubiquitous:

$ ls | pr -dt

Note that any file names with an embedded carriage return will have an extra carriage return added in the output. (I believe that problem occurs with all of the solutions presented so far.)

查看更多
登录 后发表回答