Bash变量的做法

时间:2015-08-24 20:54:23

标签: bash awk sed grep

我有这个python脚本:

    for item in users:
        User.objects.create(
                website = item['']
                myspace_name = item['']
                last_name = item['']
                public_favorites_count = item['']
                followings_count = item['']
                full_name = item['']
                user_id = item['']
                city = item['']
                first_name = item['']
                track_count = item['']
                playlist_count = item['']
                discogs_name = item['']
                followers_count = item['']
                online = item['']
                username = item['']
                description = item['']
                kind = item['']
                last_modified = item['']
                website_title = item['']
                permalink_url = item['']
                permalink = item['']
                country = item['']
                uri = item['']
                avatar_url = item['']
                plan = item['']
            )

目标是编写一个脚本来更改文件,如:

...
                    avatar_url = item['avatar_url']
                    plan = item['plan']
...

我试过这个,但它不起作用。

#!/bin/bash


FILE = "/home/user/metadata.py"

clear

declare -a array
declare -i i=0

grep 'item\[' /home/user/metadata.py | while read line

do
    array[i] = $(awk '{print $1}')
    sed "s/item\['/item\['array[$i]/" 
    let i++
done

任何帮助,请更正脚本,如果有更好的解决方案。感谢

1 个答案:

答案 0 :(得分:0)

awk one liner(更容易将它放在一个单独的文件中,然后找出要逃脱的引号):

$ cat a.awk
/.*= *item\[''\]/ {sub("''", "'"$1"'")}1

$ awk -f a.awk a.py
for item in users:
    User.objects.create(
            website = item['website']
            myspace_name = item['myspace_name']
            last_name = item['last_name']
            public_favorites_count = item['public_favorites_count']
            followings_count = item['followings_count']
            full_name = item['full_name']
            user_id = item['user_id']
            city = item['city']
            first_name = item['first_name']
            track_count = item['track_count']
            playlist_count = item['playlist_count']
            discogs_name = item['discogs_name']
            followers_count = item['followers_count']
            online = item['online']
            username = item['username']
            description = item['description']
            kind = item['kind']
            last_modified = item['last_modified']
            website_title = item['website_title']
            permalink_url = item['permalink_url']
            permalink = item['permalink']
            country = item['country']
            uri = item['uri']
            avatar_url = item['avatar_url']
            plan = item['plan']
        )