Scripting help- cut the string

Hi
I am having a file with the following content(its created by ls of a directory):
-rw-r----- 1 321 321 0 Oct 14 10:41 xcv23456
-rw-r----- 1 321 321 0 Oct 14 10:41 xcv23457
-rw-r----- 1 321 321 0 Oct 14 10:41 xcv23458
-rw-r----- 1 321 321 0 Oct 14 12:19 xcv23459
-rw-r----- 1 321 321 0 Oct 15 11:19 xcv23460

last column ie 9th column contains the file names.
I am searching for a script which can cut the last 5 digits of each row and store it in a seperate variable.

Thnks in advance

The key here is to use "awk" to extract the filename rather than "cut" because when the day of the month in the timestamp is a single digit the filename will be in a different position.

0ne way:
cat myfile.txt | awk '{print $9}' | cut -c4-8 | while read number
do
       echo "${number}"
done

Or if you prefer redirection to cat:
cat myfile.txt | awk '{print $9}' | cut -c4-8 | while read number
do
       echo "${number}"
done < myfile.txt

Or we could read the file directly with "awk":
awk '{print $9}' myfile.txt| cut -c4-8 | while read number
do
       echo "${number}"
done
1 Like
$ ruby -ne 'puts $_[-6..-1]' file
23456
23457
23458
23459
23460

Thnaks :slight_smile: it works

assuming your fields have fixed width ...

cut -c 40- yourfile | while read line ; do ; echo "num=$line" ; done
$
$ cat f27
-rw-r----- 1 321 321 0 Oct 14 10:41 xcv23456
-rw-r----- 1 321 321 0 Oct 14 10:41 xcv23457
-rw-r----- 1 321 321 0 Oct 14 10:41 xcv23458
-rw-r----- 1 321 321 0 Oct 14 12:19 xcv23459
-rw-r----- 1 321 321 0 Oct 15 11:19 xcv23460
$
$
$ perl -plne 's/^.*(.{5})$/$1/' f27
23456
23457
23458
23459
23460
$
$
$ perl -plne '$_=substr($_,-5)' f27
23456
23457
23458
23459
23460
$
$

tyler_durden

1 Like

Thanks everyone. :slight_smile: