Martim Correia
Martim Correia

Reputation: 505

error while priting the name of files of a directory in bash

So i have this basic program and basically what it does is go to an input folder and print the name of every file there and a number. The problem is that its printing the full path of the file and i only want the name of the file and for some reason the names are not sorted.

Expected output:

$ ./my_script.sh inputs bye 2
InputFile=test1.txt Num=1
InputFile=test1.txt Num=2
InputFile=test2.txt Num=1
InputFile=test2.txt Num=2
InputFile=test3.txt Num=1
InputFile=test3.txt Num=2
InputFile=test4.txt Num=1
InputFile=test4.txt Num=2

My output:

$ ./my_script.sh inputs bye 2
InputFile=inputs/test1.txt Num=1
InputFile=inputs/test1.txt Num=2
InputFile=inputs/test2.txt Num=1
InputFile=inputs/test2.txt Num=2
InputFile=inputs/test4.txt Num=1
InputFile=inputs/test4.txt Num=2
InputFile=inputs/test3.txt Num=1
InputFile=inputs/test3.txt Num=2

Program:

#!/bin/bash

Word1="${1}"
Word2="${2}"
Num="${3}"
for file in $(ls ${Word1}/*.txt)
do
    for i in $(seq 1 ${Num})
    do
        echo "InputFile="${file} "Num="${i}
    done
done

Upvotes: 0

Views: 33

Answers (2)

tshiono
tshiono

Reputation: 22012

Would you please try the following:

Word1=$1
Word2=$2
Num=$3
for file in "$Word1/"*.txt; do
    for i in $(seq 1 "$Num"); do
        file=${file##*/}            # remove rightmost "/" and leading characters
        echo "InputFile=${file} Num=${i}"
    done
done
  • As Raman Sailopal comments, it is an antipattern to parse the output of ls. In this case you can use for loop instead, as above.
  • You are not double-quoting variables where you should, while double-quoting where it is not mandatory.
  • You can extract the filename out of the fullpath with file=${file##*/}.

Upvotes: 0

Raman Sailopal
Raman Sailopal

Reputation: 12877

Don't parse the output of ls. Instead use find and so:

find . -name "$word1*.txt" -printf "%f\n" 

%f will display the filename only.

You can also utilise awk to achieve what you need.

find -name "$word1*" -printf "%f\n" | awk -v num=$3 '{ for (i=1;i<=num;i++) { print "InputFile="$0" Num="num }}'

Pipe the output from the find command into awk. Loop from one to the number determined by num (a variable passed into awk and set to passed parameter $3) printing each line output from find in the required format.

Upvotes: 1

Related Questions