如何使用awk解析名称中带有空格的文件
我创建了一个脚本,它将文件名拆分为数据库插入的组件:
find . -name "R*VER" | while read fname
do
awk -v squote="'" -v base=${fname##*/} '
{
split( base, a, "~" );
printf( "INSERT INTO REPORT (COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8)\n" );
str = sprintf( "VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")", base, a[1], a[2], a[3], a[7], a[8], a[9], a[10] );
gsub( "\"", squote, str ); # replace double quotes with singles
print str;
}'
done
直到今天它都运行良好。引入了新的文件名,其中 a[1]
包含空格,例如 something here~...
。
现在,我有如下所示的混合文件:
R1~blah~blahblah...VER
和 R 4~blah~blahblah...VER
我想从 find 修改
来find
。 -name "R*VER"查找 . -name "* *"
但这将排除文件名中没有空格的所有文件。
做到这一点最有效的方法是什么?
I have created a script which splits filenames into components for database inserts:
find . -name "R*VER" | while read fname
do
awk -v squote="'" -v base=${fname##*/} '
{
split( base, a, "~" );
printf( "INSERT INTO REPORT (COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8)\n" );
str = sprintf( "VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")", base, a[1], a[2], a[3], a[7], a[8], a[9], a[10] );
gsub( "\"", squote, str ); # replace double quotes with singles
print str;
}'
done
It worked great until today. New file names have introduced where a[1]
contains a space e.g something here~...
.
Now, I have a mix of files that look like this:
R1~blah~blahblah...VER
andR 4~blah~blahblah...VER
I want to modify find
from find . -name "R*VER"
to find . -name "* *"
but this will exclude all the files without spaces in the filename.
What is the most efficient way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 内部字段分隔符变量 $IFS 设置为换行符,而不是比一个空间。例子:
Set the Internal Field Separtor variable, $IFS, to a newline, rather than a space. Example:
如何在命令行上包含变量,例如:
awk ... base="$fname"
不知道代码中的附加
##*/
是什么不过确实如此。也许是一些 bash 扩展...如果您确定没问题,请将其全部用双引号引起来:
base="${fname##*/}"
What about enclosing the variable on the command line, like:
awk ... base="$fname"
Don't know what that additional
##*/
in your code does, though. Maybe some bash extension...If you are sure it is OK, enclose it all in double quotes too:
base="${fname##*/}"