2

I have a text file in the following format:

001|fileA
002|fileA
003|fileA
004|fileB
005|fileB
006|fileC
.
.
.
xxx|fileX

I need to split this file into the files corresponding to each "|". The names of new files like fileA ,fileB,fileC...fileX .

3

try

 awk -F\| '{ print $1 > $2 ; }' file

where

  • -F\| tell awk to use | as separator, | need to be escaped.
  • > $2 redirect print to $2's value.

in case of many ( > 10 ) files :

for x in $(awk -F\| '!a[$2]++ { print $2}' file)
do
    awk -F\| -v f="$x" '$2 == f { print $1}' file > "$x"
done
  • first awk merely list uniq filename
  • 52 files are OK, this might get slow if hundreds of files.

another alternative, provided field are "safe" to put in shell

awk -F\| '{printf "echo %s >> %s\n",$1,$2;}' file | bash
  • be sure to delete fileX before, in case of re-run.
1
  • This code will work when there are not more than 10 files. Because of 52 files, it responds to "awk: too many output files 10" – Watcharin Chimmachuy Jun 16 '16 at 7:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.