Ale*_*ern 116 linux command-line ls
我应该只用这种结构回显文件或目录的名称:
ls -Al | while read string
do
...
done
Run Code Online (Sandbox Code Playgroud)
ls -Al 输出 :
drwxr-xr-x 12 s162103 studs 12 march 28 12:49 personal domain
drwxr-xr-x 2 s162103 studs 3 march 28 22:32 public_html
drwxr-xr-x 7 s162103 studs 8 march 28 13:59 WebApplication1
Run Code Online (Sandbox Code Playgroud)
例如,如果我尝试:
ls -Al | while read string
do
echo "$string" | awk '{print $9}
done
Run Code Online (Sandbox Code Playgroud)
然后只输出没有空格的文件和目录。如果文件或目录有“个人域”之类的空格,则只有“个人”一词。
我需要非常简单的解决方案。也许有比 awk 更好的解决方案。
ter*_*don 139
你真的不应该解析ls. 如果这是家庭作业并且你被要求这样做,你的教授不知道他们在说什么。你为什么不做这样的事情:
find ./ -printf "%f\n"
Run Code Online (Sandbox Code Playgroud)
或者
for n in *; do printf '%s\n' "$n"; done
Run Code Online (Sandbox Code Playgroud)
如果你真的很想使用ls,你可以通过做这样的事情来使它更健壮一点:
ls -lA | awk -F':[0-9]* ' '/:/{print $2}'
Run Code Online (Sandbox Code Playgroud)
如果您坚持以错误的、危险的方式进行操作并且只需要使用while循环,请执行以下操作:
ls -Al | while IFS= read -r string; do echo "$string" |
awk -F':[0-9]* ' '/:/{print $2}'; done
Run Code Online (Sandbox Code Playgroud)
说真的,只是不要。
bah*_*mat 131
有什么原因ls -A1* 不起作用吗?
例如:
$ touch file1 file2 file\ with\ spaces
$ ls -Al
total 0
-rw-r--r-- 1 bahamat bahamat 0 Mar 30 22:31 file1
-rw-r--r-- 1 bahamat bahamat 0 Mar 30 22:31 file2
-rw-r--r-- 1 bahamat bahamat 0 Mar 30 22:31 file with spaces
$ ls -A1
file1
file2
file with spaces
$
Run Code Online (Sandbox Code Playgroud)
* 注意:这是一个大写字母 A 和数字 1。
小智 80
我想知道为什么没有人提到这个简单的命令:
ls -a | sort
Run Code Online (Sandbox Code Playgroud)
您无法解析 的输出ls,更不用说ls -l因为换行了,就像空格与文件名中的任何字符一样有效。此外,您还需要考虑具有类似... foo -> bar.
-l如果您只想要文件名,为什么还要使用?
做就是了:
for file in *; do
...
done
Run Code Online (Sandbox Code Playgroud)
如果要包含点文件(除了.和..),取决于外壳:
zsh:
for file in *(ND); do
...
done
Run Code Online (Sandbox Code Playgroud)
bash:
shopt -s nullglob dotglob
for file in *; do
...
done
Run Code Online (Sandbox Code Playgroud)
ksh93:
FIGNORE='@(.|..)'
for file in ~(N)*; do
...
done
Run Code Online (Sandbox Code Playgroud)
POSIXly:
for file in .[!.]* ..?* *; do
[ -e "$file" ] || [ -L "$file" ] || continue
...
done
Run Code Online (Sandbox Code Playgroud)