Search code examples
grepshcut

cut text file and get the first field bash


i had a problem with using grep, or cut command to get out the files size i have that file :

   4096 Feb 15 21:52 f1
      0 Feb 15 18:24 f4
6928808 Feb 10 16:59 install_flash_player_11_linux.i386.tar.gz
     87 Feb 14 18:43 sc1.sh
    281 Feb 14 19:11 sc2.sh
    168 Feb 14 21:40 sc3.sh
    345 Feb 15 21:15 sc4.sh
    278 Feb 15 19:27 sc4.sh~
      6 Feb 15 18:27 sc5.sh
    472 Feb 16 11:01 sc6.sh
    375 Feb 16 11:01 sc6.sh~
    359 Feb 17 01:18 sc7.sh
    358 Feb 17 01:17 sc7.sh~
    230 Feb 16 09:31 toUppefi.sh
    230 Feb 16 02:07 toUppefi.sh~

i need to get off only the first numbers every time for example :

4096
0
...

I used ls -l . | cut -d" " -f5 (for list of files!) to get only size but the result is spaces ! because of the space before numbers ! and when i use delimiter " " and -f it doesn't work it gives only the most biggest number that begin from the left side , i hope u understand my problem


Solution

  • You could do ls -l . | awk '{print $1}', but you should follow the general advice advice to avoid parsing the output of ls.

    The usual way to avoid parsing the output of ls is to loop over the files to get the information you need. To get the size of the files, you could use wc -c.

    for file in *; do
        if [ -e "$file" ]; then   #test if file exists to avoid problems with an empty directory
            wc -c "$file"
        fi
    done
    

    If you really only need the size - just pipe through awk.

    for file in *; do
        if [ -e "$file" ]; then
            wc -c "$file" | awk '{print $1}'
        fi
    done
    

    Getting the size without using awk (@tripleee suggestion):

    for file in *; do
        if [ -e "$file" ]; then
            wc -c < "$file"
        fi
    done