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 ))'
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
JohnnyF
  • 953
  • 2
  • 13
  • 30
  • 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`. – Jonathan Leffler Dec 20 '14 at 09:23
  • thx, but speed is not really inportent for this task, just want it to do the right job :) – JohnnyF Dec 20 '14 at 09:25

3 Answers3

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 ))
Johnsyweb
  • 121,480
  • 23
  • 172
  • 229
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.

Community
  • 1
  • 1
abelenky
  • 58,532
  • 22
  • 99
  • 149
  • 3
    Modern style is to use `$(…)` in preference to backticks (` … `), and not just because it is hell getting backticks to appear in comments under Markdown. – Jonathan Leffler Dec 20 '14 at 09:22
-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
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
armnotstrong
  • 7,047
  • 10
  • 51
  • 108