bashawkxargs

Bash Shell awk/xargs magic


I'm trying to learn a little awk foo. I have a CSV where each line is of the format partial_file_name,file_path. My goal is to find the files (based on partial name) and move them to their respective new paths. I wanted to combine the forces of find,awk and mv to achieve this but I'm stuck implementing. I wanted to use awk to separate the terms from the csv file so that I could do something like
find . -name '*$1*' -print | xargs mv {} $2{}
where $1 and $2 are the split terms from the csv file. Anyone have any ideas?
-peace


Solution

  • I think you've got things mixed up here. {} can only be used in find, and only once. I.e you cannot do something like find -name '*.jpg' -exec mv {} {}.png.

    Do this:

    $ cat korv
    foo.txt,/hello/
    bar.jpg,/mullo/
    $ awk -F, '{print $1 " " $2}' korv
    foo.txt /hello/
    bar.jpg /mullo/
    

    -F sets the delimiter, so the above will split using ",". Next, add * to the filenames:

    $ awk -F, '{print "*"$1"*" " " $2}' korv
    *foo.txt* /hello/
    *bar.jpg* /mullo/
    **
    

    This shows I have an empty line. We don't want this match, so we add a rule:

    $ awk -F, '/[a-z]/{print "*"$1"*" " " $2}' korv
    *foo.txt* /hello/
    *bar.jpg* /mullo/
    

    Looks good, so encapsulate all this to mv using a subshell:

    $ mv $(awk -F, '/[a-z]/{print "*"$1"*" " " $2}' korv)
    $
    

    Done.