2

I am trying to make a small script that will give me the File names without the $2 first and $3 last names in a $1 directory

I have this code

#!/bin/bash
TOTFILES=find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l
find "$1" -maxdepth 1 -type f -exec basename {} ';' | sort |
    head -n (( TOTFILES-$3 )) | tail -n (( TOTFILES-$3-$2 ))

My main problem is that I can't assign TOTFILES with the output of that long line.

I think if I can get that value assigned, it will work (hopefully) :)

PS: I don't know if I used

(( TOTFILES-$3 ))

right, to get the value.

Thanks for the fast answer. Now I get a new problem; I guess (( )) is not the right way to get number

./middleFiles: line 5: syntax error near unexpected token `('
./middleFiles: line 5: `find "$1" -maxdepth 1 -type f -exec basename {} ';' | sort | head -n (( TOTFILES-$3 ))  | tail -n (( TOTFILES-$3-$2 ))'
2
  • Note that the exec basename only slows things down unless you think directory names might contain newlines. Otherwise, you could be just as accurate with -print instead of -exec. Commented Dec 20, 2014 at 9:23
  • thx, but speed is not really inportent for this task, just want it to do the right job :) Commented Dec 20, 2014 at 9:25

3 Answers 3

3

Command substitution assigns the output of a command:

TOTFILES=$(find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l)

Arithmetic expansion will get you the argument to head and tail:

head -n $(( $TOTFILES - $3 ))
Sign up to request clarification or add additional context in comments.

3 Comments

exelent, but i have a follow up question ( i addd the question) i will be more then happy if you will be able to help me :)
I was still editing my answer when you posted your follow-up :-)
Dude, you really saved me, broke my head around, well thx a lot
0

I believe you need backticks around the expression you want evaluated.

TOTFILES=`find "$1" -maxdepth 1 -type f -exec basename {} ';' | wc -l`

See this answer for details.

1 Comment

Modern style is to use $(…) in preference to backticks (` … `), and not just because it is hell getting backticks to appear in comments under Markdown.
-2

I think best way is to assign filenames to an array. According to your code, you just want depth = 1 so simple ls trick will do the job

#!/bin/bash

TOTFILES=($(ls -p $1 | grep -v / | sort -n)

# and you can use the array like this
for file in ${TOTFILES[*]};do 
    echo $file;
done
# leave you to get a subset of the ${ToTFILES}
# refer to http://stackoverflow.com/questions/1335815/how-to-slice-an-array-in-bash

2 Comments

Please don't encourage people to parse the output of ls
thanks, accept that downvote, but life is dangerous anyway :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.