使用头部和切割定义变量

时间:2017-09-23 18:51:34

标签: bash variables

可能是一个简单的问题,我是bash的新手,并且能够找到我问题的解决方案。

我正在编写以下脚本:

for file in `ls *.map`; do 

ID=${file%.map}

convertf -p ${ID}_par #this is a program that I use, no problem

NAME=head -n 1 ${ID}.ind | cut -f1 -d":" #Now: This step is the problem: don't seem to be able to make a proper NAME function. I just want to take the first column of the first line of the file ${ID}.ind

它给了我回报      第5行:糟糕的替代 有什么帮助吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

您的代码中存在一些问题:

  • for file in `ls *.map`没有做你想要的。它会失败,例如如果任何文件名包含空格或*,但还有更多。有关详细信息,请参阅http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29

    您应该只使用for file in *.map

  • ALL_UPPERCASE名称通常用于系统变量和内置shell变量。使用小写字母表示您自己的名字。

那就是说,

for file in *.map; do 
    id="${file%.map}"
    convertf -p "${id}_par"
    name="$(head -n 1 "${id}.ind" | cut -f1 -d":")"
...

看起来会起作用。我们只使用$( cmd )来捕获字符串中命令的输出。