-2

I have the following list of folders having two words in name separate by a space

WEB TEH
COMPUTER SCIENCE
UNIX LINUX

I would create a shell script, this script can browse the directory and extract the first and the second word from each folder ,

and put each one of extracted word into a text file (each of word in one line)

file1.txt contain :

WEB
COMPUTER
UNIX

and file2.txt contain:

TECH
SCIENCE
LINUX

Thank You

EDIT:

I create this script :

#!/bin/bash

# Read folder name and put it in file
read -p "Enter Your Path: "  Path
for entry in $Path
do
   echo -e "$entry">>file.txt
done

#Browse file and echo line
file="/home/user/file.txt"
while IFS= read -r line
do
    printf '%s\n' "$line"
done 
<"$file"

but i cant' get the folder name (in this script i get the path)

and i don't know how to extract the two word


EDIT 2:

#!/bin/bash
# Read and put nom/prénom dans un fichier
read -p "Enter Your Path: "  Path
for entry in $Path
do
   word= basename $entry 
   echo -e "$word">>file.txt
   cat file.txt | cut -d ' ' -f 1 > file1.txt
   cat file.txt | cut -d ' ' -f 2 > file2.txt
done
#Browse folder 
file="/home/user/file.txt"
#while IFS= read -r line
#do
#       printf '%s\n' "$line"
#done <"$file"

the output of script is :

COMPUTER
UNIX
WEB

when i execute cat file1.txt , i don't see the content of fike


EDIT 3 :

I can show the name of folder

for entry in $path
do
 echo ${entry##*/}>>file.txt
done

but , how i can extract the two word ?

1

try this:

#!/bin/bash
ls "$1" > file.txt
cat file.txt | cut -d ' ' -f 1 > file1.txt
cat file.txt | cut -d ' ' -f 2 > file2.txt

Save it somewhere and use ./script_name /home or something like that.

Edit: follow these steps

  1. Create a file named script with the the above commands in the current directory.
  2. Run chmod a+x script. (this makes your script executable)
  3. Run ./script DIR_NAME. (replace DIR_NAME with your desired directory)
  4. This will create two files file1.txt and file2.txt in the same directory as of script
  • when i execute " cat file1.txt" , i dont' see the content of file – YOU CHT LEE Oct 14 '18 at 9:20
  • @YOUCHTLEE please elaborate a little more. – scipsycho Oct 14 '18 at 9:21
  • I'am noob with shell/sctipt – YOU CHT LEE Oct 14 '18 at 9:24
  • It should work fine! can you tell me exactly what you are doing? – scipsycho Oct 14 '18 at 9:24
  • @YOUCHTLEE I added the steps you should follow. for one thing, you don't need a while loop. do as I did. Besides, in your answer below, you are using > file1.txt that actually writes to a file as if it was empty. Use >> file1.txt – scipsycho Oct 14 '18 at 9:37

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.