开发者

How to parse file with space in its name with Awk

开发者 https://www.devze.com 2023-03-28 07:26 出处:网络
I have created a script which splits filenames into components for database inserts: find . -name \"R*VER\"| while read fname

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 and R 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?


Set the Internal Field Separtor variable, $IFS, to a newline, rather than a space. Example:

#!/bin/sh
filenames=`ls`
IFS=$'\n'
for fname in $filenames ; do
    echo "$fname: "
    awk '{print $0}' $fname
done


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##*/}"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号