Regular expressions and shell scripts

I have knowledge of regular expressions and shell scripts. I have a directory / work / test /, where I have several files, such as the following files: needstc_30554-r-00051, profilemd5_30323-r-00053, unchanged_30394-r-00053.

I want to extract the first number ONLY from files that start with the unchanged file unchanged_30397-r-30554, and the number in this case will be 30397.

I played with regular expressions and was able to extract the identifier from a single file with the following:

    str='profiles_060315091024_30398-r-00006.avro'
    myvar=$(awk -F'[_-]' '{print $3}' <<< "$str")

So my question is:

How can I go into this directory and get the first number only from files that start with unchanged?

thanks

+4
source share
4 answers

find, , cut, . for , , -, , . while .

find /work/test -type f -name 'unchanged*' | \
    cut -d_ -f2 | cut -d- -f1 | \
    while read fname;do echo $fname;done

, , , while - , - .

find - ; find . "-type f" . -name , .

"cut" - . "-d_" , "-f2" , ; . , ; . , , while. read , .

, , , , , .

+1

Grep ls AWK ( ).

ls | grep '^unchanged_' | awk -F'[_-]' '{print $2}'
  • ls:
  • grep: ( )
  • awk: (: $2)
+2

1) : unchanged_*.

2) . , - .

:

cd /work/test/

for file in unchanged_*; do
    number=${file#unchanged_}   # remove "unchanged_"
    number=${number%%-*}        # remove everything after dash

    echo "$number"
done
+1

perl:

#!/usr/bin/env perl

use strict;
use warnings;

#iterate files in current directory matching file spec
for ( glob("./unchanged_*") ) {
    #regular expression match first instance of 'one or more digits' into
    # $number
    if ( my ($number) = m/(\d+)/ ) {
        #print if that regex matched
        print $number, "\n";
    }
}

, .

0

Source: https://habr.com/ru/post/1607655/


All Articles