dpsdce
dpsdce

Reputation: 5450

Create directories by reading file as a input in bash

i have a input file say temp.txt with content as following

  2013-08-13 /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-03-01
  2013-08-14 /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-03-02
  2013-08-15 /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-03-03
  2013-07-30 /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-07-30
  2013-07-31 /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-07-31
  2013-08-16 /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-08-13

I need to iterate over this file and create directories with the date specified at the begining of the line and then move the data in the directory specified after the date to this particular directory..

for example: for first line i need to do a

mkdir "2013-08-13" 

and then

mv /data/PSG/LZ/INVENTORY_FORECAST/load_date=2013-03-01/  2013-08-13

i am trying to do it with

  cat temp.txt | while read line ; do  mkdir "echo $line | awk '{print $0}'"; done;

tried to use line as a array using

  cat temp.txt | while read line; do lineArray=($line) echo $line, ${lineArray[0]}, $lineArray[1];  done;

but none of these seem to work.. any idea about how to approach this problem ?

Upvotes: 3

Views: 4094

Answers (2)

user000001
user000001

Reputation: 33317

You can read the lines into two variables. For example:

while read -r date path # reads the lines of temp.txt one by one, 
                        # and sets the first word to the variable "date", 
                        # and the remaining words to the variable "path"
do 
    mkdir -p -- "$date"  # creates a directory named "$date".
    mv -- "$path" "$date" # moves the file from the "$path" variable to the "$date folder"
done < temp.txt   # here we set the input of the while loop to the temp.txt file

The -- option is used so that if a file starts with - it will not be interpreted as an option, but will be treated literally.

The -p or --parents makes the mkdir command to not trow an error if the directory exists, and to make parent directories if necessary.

Upvotes: 6

iamauser
iamauser

Reputation: 11469

This should do the job:

while read line
do
export dname=`echo $line | awk '{print $1}'`
mkdir -p "$dname"
export fname=`echo $line | awk '{print $2}'`
mv "$fname" "$dname"
done < temp.txt

Upvotes: 0

Related Questions