Thursday, September 17, 2009

Bash script to copy required files


Contents of my "inputdir" is a set of files with filename like this:

$ ls -1 inputdir/
log.10.16.1253168140.txt
log.11.5.1253168345.txt
log.11.9.1253168347.txt
log.12.1.1253168347.txt
log.19.1.1253168140.txt

Directory "testcfgs" contains a set of config xmls.

$ ls -1 testcfgs/
cfg_10_16.xml
cfg_10_5.xml
cfg_11_5.xml
cfg_11_9.xml
cfg_12_1.xml
cfg_19_1.xml
cfg_19_2.xml
cfg_91_9.xml

Required:

For each file of name "log.X.Y.timestamp.txt" in "inputdir", copy the corresponding "cfg_X_Y.xml" config file from "testcfgs" to a directory say "requiredcfgs".

A simple practical bash one liner script:

$ for filename in $(ls -1 inputdir/)
> do
> X=$(echo "$filename" | cut -d"." -f2)
> Y=$(echo "$filename" | cut -d"." -f3)
> cp testcfgs/cfg_$X\_$Y.xml requiredcfgs/
> done

The two lines above for finding X and Y value can be replaced by a single line using 'eval with awk', like this:

$ for filename in $(ls -1 inputdir/)
> do
> eval $(echo "$filename" | awk -F "." '{print "X="$2";Y="$3}')
> cp testcfgs/cfg_$X\_$Y.xml requiredcfgs/
> done

Contents of "requiredcfgs" directory after execution of the above bash script.

$ ls -1 requiredcfgs/
cfg_10_16.xml
cfg_11_5.xml
cfg_11_9.xml
cfg_12_1.xml
cfg_19_1.xml

Related post on eval with awk:

- Subdivide an ip address - assign each part to an variable using awk

3 comments:

Mahesh Kharvi said...

ls -1 inputdir/ | awk -F. '{"cp testcfgs/cfg_"$2"_"$3".xml requiredcfgs/" | getline}'

something different :)

Jadu Saikia said...

@Mahesh, this is an excellent one liner. Thanks.

sathiyamoorthy said...

hai admin this is very nice information for me..i didnt read this before...now i got some idea about this...thanks for sharing...please visit my blog in that i too have some useful informations..
http://netwalker.limewebs.com/
Its for E-Learning blog who want to really develop their Knowledge.And you can earn online money..Visit my blog..

© Jadu Saikia www.UNIXCL.com