简体   繁体   中英

linux create directories and move corresponding files to the directories

I have a text file listed the directory names and what files should included inside.

my text file:
SRS000111    ERR1045156     
SRS000112    ERR1045188     
SRS000123    ERR1045204     
SRS000134    ERR1045237  ERR1045238  ERR1045239
SRS000154    ERR1045255  ERR1045256 
SRS000168    ERR1045260  ERR1045261  ERR1045262
...          ...         ...
SRS001567    ERR1547451  ERR1547676

now I want to create all the directories using the first column of the text file but I don't know how to do the for loop.

for filename in cat file.txt | awk -F, '{print $1}'; do mkdir ${filename}; done

but it goes to error.

second I have all the ERR files and I want to move them to the corresponding directories according to the text file. I have not any idea how to do this part.

You have to make system calls from awk for mkdir and mv files

This awk would do

awk 'FNR>1{system("mkdir \"" $1 "\""); for(i=2; i<=NF; i++) system("mv \"" $i "\" " "\"" $1 "\"")}' file

FNR>1 because we don't want to create directory for first line ie header names in your CSV file

Note : Run this command from the directory where all the filenames as mentioned in your source/input file are present. This will create directories there itself and will move all the files in those newly created directories.

I recommend you read the file, split the folder name columns and file name columns and makes de directories and the movements.

This script makes it:

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
  dir=$(echo "$line" | awk '{print $1}')
  files=$(echo "$line" | awk '{$1=""; print $0}')

  mkdir $dir
  mv $files $dir/
done < myfile.txt

Is not to complicated but if you have questions about it you can make me any question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM