Search code examples
grepcutdivide

Grep and Cut Command and divide string


I have a grep command that gives the following string:

20121121001100 18 0 16 2 18

but I would like to modify this string to get

20121121 001 18 0 16 2 18

the above value are being extracted by the following:

for i in `ls -1 file.txt | sort`; do echo $i`
grep datetime $i | wc -l ``
grep abc $i | wc -l ``
grep def $i | wc -l ``
grep ghi $i | wc -l ``
grep jkl $i | wc -l ` ; done | cut -c9-500

cut -c9-500 is used because the original string is in the form of

datetime20121121001100 18 0 16 2 18

and cut -c9-500 returns

20121121001100 18 0 16 2 18

Can someone please help me to get

20121121 001 18 0 16 2 18

(ie remove the last 3 digits from the date part)


Solution

  • Most of what you want/do can be accomplished with awk. But for the minimum you want:

    for i in `ls -1 file.txt | sort`; do echo $i`
    grep datetime $i | wc -l ``
    grep abc $i | wc -l ``
    grep def $i | wc -l ``
    grep ghi $i | wc -l ``
    grep jkl $i | wc -l ` ; done | cut -c9-500 | awk '{print substr($0,1,11) substr($0,15) }'
    

    awk is very capable at text processing.

    Edit: I'm not sure of what are you doing, but, basicly this does (almost) the same:

    awk 'FILENAME != oldfilename {oldfilename = FILENAME; dt = 0 ; a = 0; d = 0; g = 0; j = 0}
         /datetime/ {dt++}
         /abc/ {a++}
         /def/ {d++}
         /ghi/ {g++}
         /j/ {j++}
         END {print FILENAME, dt, a, d, g, j}' *
    

    And it's faster, fewer processes, etc... Basically awk process the file, counts the occurences of the specified strings, and when it finishes the file (after the last line) prints the report.

    Changed specs:

    for i in `ls -1 file.txt | sort`; do echo $i`
    grep datetime $i | wc -l ``
    grep abc $i | wc -l ``
    grep def $i | wc -l ``
    grep ghi $i | wc -l ``
    grep jkl $i | wc -l ` ; done | cut -c9-500 | awk '{print substr($0,1,8) " " substr($0,9,4) substr($0,15) }'