Linux:对一批文件运行命令,输出文件匹配

don*_*ton 4 linux script bash batch command-line

一个简单的任务:给定一个文件目录和一个将一个文件作为输入并生成一个文件作为输出的命令,我想一次处理一个目录中的所有文件,并用相应的匹配名称(带有新的扩展名)输出它们。

所以如果命令通常是:

convert -input sourceFile.ext -output destFile.out
Run Code Online (Sandbox Code Playgroud)

我想处理一个文件夹

file1.ext, file2.ext, etc.
Run Code Online (Sandbox Code Playgroud)

并在相同的目录中生成文件

file1.out, file2.out, etc.
Run Code Online (Sandbox Code Playgroud)

有没有办法在终端中做到这一点而无需编写 bash 脚本?我对脚本不是很熟悉,所以任何简单的解决方案都将不胜感激。

gle*_*man 11

不使用basename

for file in *.ext; do convert -input "$file" -output "${file/%ext/out}"; done
Run Code Online (Sandbox Code Playgroud)

请参阅http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion


小智 5

查看find命令

一定要cd到你的输入目录。

cd input_directory
find . -iname "*.ext" -exec convert -input {} -output {}.out \;
Run Code Online (Sandbox Code Playgroud)

这将导致.out被附加到您的输入文件的名称。获取您声明的输出文件我还没有弄清楚。

find在运行-exec改变事物之前尝试做什么总是明智的。

cd input_directory    
find  .  -iname "*.ext"  -type f  -exec ls -l {} \;
Run Code Online (Sandbox Code Playgroud)

会做一种“试运行”。

  • -exec 运行什么命令
  • {}找到了什么文件;一次一个
  • \; 需要用它来结束一个 -exec

我的有限实验表明您不需要引用 {}

$ find . -type f -exec ls -bl {} \;  
-rw-r--r--. 1 me me 0 Oct 20 19:03 ./a\ b\ c.txt  
-rw-r--r--. 1 me me 0 Oct 20 19:03 ./abc.txt  

$ ls -bl
total 0
-rw-r--r--. 1 me 0 Oct 20 19:03 a\ b\ c.txt
-rw-r--r--. 1 me 0 Oct 20 19:03 abc.txt
me ~/a $`
Run Code Online (Sandbox Code Playgroud)

我有一个文本文件 help.txt,其中包含我所有难以记住的 bash 命令的提示。我将它绑定到一个简单的脚本来打印文件 .., h

这是我的查找命令列表:

# searches for all files on the system for the string you fill in between the ""
sudo find  /  -type f -exec grep -il "" {} \;
# search for all files starting with python.
find / -iname 'python*'
# search for the file type .jpeg and sort the list by date
find  ~  -iname "*.jpeg" -type f  -exec ls -l  {} \; 2>/dev/null | sort -r -k 8,8 -k 6,7M
# so I can remember the or syntax. 
find  ~  \( -iname "*.jpeg" -o -iname "*.png"  \) -type f  -exec ls -l  {} \;
Run Code Online (Sandbox Code Playgroud)