Bash variable in sed command

纵然是瞬间 提交于 2019-12-13 15:29:58

问题


I need to add an header recursively to several file according to the name of the file.

So I have tried:

for i in *file 
do     
sed -i '1 i \A;B;C;D;E;F;G;H;${i%??}' a_${i} > header_a_${i}
done

the problem is that the variable reflecting the name of the file does not expand and in the header I have ${i%??} instead of part of the name file (%?? is to remove some ending characters).

Any help would be great.


回答1:


Use double quotes:

    sed '1 i\
A;B;C;D;E;F;G;H;'"${i%??}" a_${i} > header_a_${i}

It doesn't make any sense to use -i and to redirect the output, so I've omitted -i. Also, I've added an escaped newline after the insert command. Some sed do not require the newline, but many do. However, it seems odd to use sed for this. Instead, just do:

for i in *file; do     
  { echo "A;B;C;D;E;F;G;H;${i%??}"; cat a_${i}; } > header_a_${i}
done


来源:https://stackoverflow.com/questions/11209049/bash-variable-in-sed-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!