Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk to print characters of specific index on a line

Tags:

awk

Alright, so I know it is quite simple to print specific arguments of a line using $:

$ cat file hello world  $ awk '{print $1}' file hello 

But what if I want to print chars 2 through 8? or 3 through 7? Is that possible with awk?

like image 940
Jordan Avatar asked Jul 09 '12 18:07

Jordan


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What does GSUB do in awk?

The gsub() function returns the number of substitutions made. If the variable to search and alter ( target ) is omitted, then the entire input record ( $0 ) is used.


2 Answers

awk '{print substr($0,2,6)}' file 

the syntax for substr() is

substr(string,start index,length)

like image 141
nims Avatar answered Sep 28 '22 03:09

nims


Yes. You can use substr function :

http://www.starlink.rl.ac.uk/docs/sc4.htx/node38.html

In your case - for print chars from 2 through 8:

echo "hello" | awk '{ print substr( $0, 2, 6 ) }' 

result is:

ello

like image 31
nick Avatar answered Sep 28 '22 01:09

nick