The basics of using cut awk grep and sed

I am trying to extract a year from this output:

sam@sam-laptop:~/shell$ date
Mon Feb  8 21:57:00 CET 2010

sam@sam-laptop:~/shell$ date | cut -d' ' -f7
2010

sam@sam-laptop:~/shell$ date | awk '{print $6}'
2010

Are there other ways to get the same result? using perhaps grep, sed, etc.? Mercy!

+3
source share
6 answers

Some options sed:

date | sed 's/.* //'

date | sed 's/.*\(....\)$/\1/'

date | sed 's/.*\(.\{4\}\)$/\1/'

date | sed -r 's/.*(.{4})$/\1/'

date | sed -r 's/.*([[:digit:]]{4})$/\1/'
+2
source

If you are really looking for the current year from date, you can simply run it directly.

date +%Y

No further processing is required. :)


Update: text processing comments (since the OP is looking for them)

cut/ awk/ sedAre perfect for drawing lines of text. grepSuitable for finding the right strings.

( ) bash - , , .

$ MYDATE=`date`
$ echo $MYDATE
Mon Feb 8 16:28:04 EST 2010
$ echo ${MYDATE##* }
2010
+10

Grep , RE. ( ).

sed RE, , , , .

+1

Perl. sed awk (CPAN), .

Perl, , awk/sed .

+1

grep . . sed , . cut - "" /( ). , , . awk , , . awk , sed, grep, cut, 1 .

grep, pipe awk/sed .

, YEAR date, date +%Y.

date

$ date +%Y
2010

$ date | awk '{print $NF}'
2010

$ var=$(date)
$ set -- $var
$ eval echo \${${#}}
2010

, , , sed, . .

+1

GNU grep -o (--only-matching), , . Perl (-P, -perl-regexp) :

$ date | grep -oP '\d{4}'
2010
+1

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


All Articles