如何在 bash 中将前缀组合到 ls 的输出中?



假设我在父目录中有一些图像:../imagea/a.png 和 ../图片/b.png.

当我这样做时:

ls ../images
# I get
../images/a.png
../images/b.png

如何为所有这些输出添加前缀![](和后缀)

我试过了:

!ls ../images/*.png | cat
# am not sure what to do next

所需输出

![](../images/a.png)
![](../images/b.png)

感谢帮助。

最简单的解决方案是使用标准的posixfind命令printf如下所示的操作:

find ../images -name "*.png" -printf '![](%p)n'

解释:

../images- 目标目录

"*.png"- 球形图案

-printf- 将操作格式化为输出

'![](%p)n'- 格式化参数以输出完整路径名。

例:

$ ls -l
total 8
drwxrwxr-x.  3 cfrm cfrm   15 Dec 13  2018 app
drwxrwxr-x.  2 cfrm cfrm   23 Mar 24  2019 app_5811_install
drwxrwxr-x. 13 cfrm cfrm 4096 Dec 12  2018 app_58_install
drwxrwxr-x.  2 cfrm cfrm 4096 Oct  3  2018 grants
-rwx------.  1 cfrm cfrm  526 Feb 17  2019 ic_start_all.sh
-rwx------.  1 cfrm cfrm  920 Oct  4  2018 ic_status_all.sh
-rwx------.  1 cfrm cfrm  984 Sep 27  2018 ic_stop_all.sh
-rwxrwxr-x.  1 cfrm cfrm 1693 Dec 13  2018 loadTrigger.sh

$ find . -name "*.sh" -printf '![](%p)n'
![](./ic_stop_all.sh)
![](./ic_status_all.sh)
![](./loadTrigger.sh)
![](./ic_start_all.sh)

遍历 glob 模式,并打印根据需要格式化的每一行:

for filename in ../*.png; do echo '!'"[]($filename)"; done

首先,我不相信你。ls ../images将仅输出基本名称,例如:

a.png
b.png
...etc...

ls ../images/*不同的命令可以提供您显示的输出。

尽管在使用 GNU coreutilsls的系统上,例如 Linux,如果输出是终端并且文件名像您显示的那样很短,那么没有选项ls将更像多列输出:

../images/aaaaa.png   ../images/ddddd.png  ../images/ggggg.png
../images/b.png       ../images/eeeee.png  ../images/hhhhhh.png
../images/ccccc.png   ../images/f.png      ../images/iiiiii.png

除非您有一个别名(或阴影函数或脚本(强制-1(一个(选项来防止这种情况。或者实际名称(显着(更长,因为它们可能应该如此。或者你正在管道连接到某物,甚至cat,因为那样ls的输出是管道而不是终端。这些细节很重要。

在某些情况下,sed和 awk 一样好,而且通常更糟糕:

ls | sed 's/^/![](/; s/$/)/'
# sed processes a string of command(s) for each line read from stdin, 
# and writes the result to stdout (by default, -n overrides this)
# s/old/new/ is string replacement using regex (which can be complex)
# ^ in old matches the beginning of the line
# $ in old matches the end of the line
# this assumes none of your filenames contains a newline character
# which Unix permits, but is rarely done because it is quite confusing

或者由于您喜欢printf,它可以完成整个工作:

printf '![](%s)n' ../images/*
# printf takes a format string containing any mixture of literal text 
# (including backslash+letter escapes mostly the same as C et succ)
# and conversion specifiers beginning with % which each interpolate one argument
# it repeats the format as needed to handle all the arguments, so here 
# with one c.s. it repeats the format once for each argument = filename
# this 'works' even if a filename contains newline
# (but I don't think the result will work correctly as markdown)

你能试试下面的吗?

awk 'BEGIN{for(i=1;i<ARGC;i++)print "![](..",ARGV[i]")"}' ../images/*.png

输出将如下所示(其中 a,b,c....png是我为测试目的创建的测试文件(。

![](.. ../images/a.png)
![](.. ../images/b.png)
![](.. ../images/c.png)
![](.. ../images/d.png)

最新更新