简体   繁体   English

如何在BASH Shell脚本中使用sed更改数组的内容?

[英]How do you alter the contents of an array with sed in BASH shell script?

I created an array of names of all files in the current directory ending with .cpp and want to create the same array with the .cpp replaced with .o 我在当前目录中创建了以.cpp结尾的所有文件的名称数组,并希望创建以.cpp替换为.o的相同数组。

cppfield=$(ls *.cpp)
ofield=$(ls *.cpp | awk '{print}' ORS=' ' | sed s/.cpp/.o/g)

but it is not working only the first argument has the .cpp switched with .o 但是它不起作用,只有第一个参数将.cpp切换为.o

You can use pattern substitution when you expand the array: 展开数组时,可以使用模式替换:

bash> a=(a.cpp b.cpp);
bash> a=("${a[@]/%.cpp/.o}");
bash> echo "${a[@]}";
a.o b.o

Is this what you are trying to do. 这是您要尝试做的。

$ ls
a1.cpp  a2.cpp  a3.cpp  a4.cpp  a5.cpp  a6.cpp
$ cppfield=(*.cpp)
$ declare -p cppfield
declare -a cppfield='([0]="a1.cpp" [1]="a2.cpp" [2]="a3.cpp" [3]="a4.cpp" [4]="a5.cpp" [5]="a6.cpp")'
$ ofield=("${cppfield[@]/%.cpp/.o}")
$ declare -p ofield
declare -a ofield='([0]="a1.o" [1]="a2.o" [2]="a3.o" [3]="a4.o" [4]="a5.o" [5]="a6.o")'

Use globbing to fill in the array to handle filenames safely. 使用全局填充来填充数组以安全地处理文件名。 Don't parse ls 不要解析ls

Use Shell Parameter Expansion to replace .cpp with .o on every array element. 使用Shell参数扩展在每个数组元素上用.o替换.cpp

Expand an array in quotes and store the result in a new array. 展开带引号的数组并将结果存储在新数组中。

Don't use ls to get directory contents for further processing. 不要使用ls获取目录内容以进行进一步处理。 It will be hard to handle the file names which have spaces and newlines in them correctly. 正确处理其中包含空格和换行符的文件名将很困难。

Better you use find like this: 最好使用以下find

x() { sed 's/\.cpp$/.o/' <<< "$1"; }
export -f x
find . -maxdepth 1 -exec bash -c 'x "{}"' \;

Now the answer is not about arrays anymore, but that's because I want to point out that storing the output of ls in an array is already the beginning of the problem. 现在答案不再是关于数组,而是因为我想指出,将ls的输出存储在数组中已经是问题的开始。 Maybe avoid arrays for this task altogether. 也许完全避免为此任务使用数组。

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

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