简体   繁体   English

如何使用awk将文件名打印到具有特定格式的新文件?

[英]How to print filenames to a new file with a specific format using awk?

I'm trying to print a list of all jpg files in a directory to a new .txt file. 我正在尝试将目录中所有jpg文件的列表打印到新的.txt文件中。

The output format in that .txt file should look like that: 该.txt文件中的输出格式应如下所示:

<img src="filename.jpg">

Currently, I have this command: 当前,我有以下命令:

ls -al *.jpg | awk ‘{print”<img src=”$9">"}' > list_of_files.txt

But it doesn't work. 但这是行不通的。 What would be the right command to get the right formatting? 获得正确格式的正确命令是什么?

One in awk: awk中的一个:

$ awk '
BEGIN {
    for(i=1;i<ARGC;i++)                       # loop all argument files
        printf "<img src=\"%s\">\n", ARGV[i]  # output as requested
    exit                                      # never touch any files
}' *.jpg

Output sample: 输出样本:

<img src="foo.jpg">
<img src="bar.jpg">

您不需要awk或任何其他外部工具,shell可以自己完成:

printf '<img src="%s">\n' *.jpg > list_of_files.txt
ls -A1 *.jpg | awk '{print "<img src=\""$0"\">"}' > list_of_files.txt

Safe version (in case to have something like rm -rf .. .jpg in your files: 安全版本(以防文件中包含rm -rf .. .jpg的内容:

shopt -s nullglob
for f in *; do
  if [[ "$f" == *.jpg ]]; then
    echo "<img src=\""$f"\">" >> list_of_files.txt
  fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM