开发者

Realizing recognition of files/directories in bash

I want to write a script in bash, that produces a list of a directory into a file. It is necessary to mark every line as file or directory.

This is my unfinished attempt:

#!/bin/bash
if [ $# -eq 1 ]
then
 if [ -d $1 ]
 then
  touch liste.txt
  ls -l $1 | grep '^-' >> liste.txt
  ls -l $1 | grep '^d' >> liste.txt
 fi
fi

now I don t know how to print in every line "file" or "directory". Maybe there is a more elegant way to solve this.

Greetings, Haniball

Thanks Pavium,

here the finished script:

#!/bin/bash
if [ $# -eq 1 ]
then
 if [ -d $1 ]
 then
  rm liste.txt
  touch liste.txt
  ls -l $1 | grep '^-' | sed -e "s/^-/File /g" >> liste.txt
  ls -l $1 | grep '^d' | sed -e "s/^d/Directory /g" >> liste.txt
 fi
 more liste.txt
fi
开发者_运维技巧

I am sure that there a more elegant solution. Maybe grep can be thrown out, but I had to restrict the output to only lines that match the pattern.

Greetings, Haniball


You can use sed as pavium already said.

ls -l $1 | grep '^-' | sed 's/^/file: /' >> liste.txt
ls -l $1 | grep '^d' | sed 's/^/directory: /' >> liste.txt

Or in one command:

ls -l $1 | sed -n -e '/^-/{s/^/file: /p;d;}' -e '/^d/{s/^/directory: /p;d;}' > liste.txt

Or you can do something different:

for f in $1/* ; do 
  if [ -d "$f" ]; then
    echo "directory: $f" >> liste1.txt
  else
    echo "file: $f" >> liste1.txt
  fi
done


(
    find . -maxdepth 1 -mindepth 1 -type f -printf 'file %f\n' | sort
    find . -maxdepth 1 -mindepth 1 -type d -printf 'dir %f\n' | sort
) > liste.txt

But perhaps simple:

ls -l --group-directories-first

will be enough?


stat --printf="%F\t%n\n" * > file.listing
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜