46

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?

William Pursell
  • 204,365
  • 48
  • 270
  • 300
Jordan
  • 2,070
  • 6
  • 24
  • 41

3 Answers3

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

the syntax for substr() is

substr(string,start index,length)

nims
  • 3,751
  • 1
  • 23
  • 27
  • Why is the field separator `-F='\n'` necessary? Or is it? – Levon Jul 09 '12 at 18:55
  • @Levon as i thought the OP wants to find the substring of the whole record, not the field. – nims Jul 09 '12 at 19:11
  • 4
    I'm a bit confused, not trying to argue, just to get this straight for myself. `$0` is already the whole current line, so if you are taking substrings of the current whole line, I don't see why you'd have to specify `-F` .. what am I missing here? – Levon Jul 09 '12 at 19:20
  • @Levon oops! Thanks for pointing it out. :) editing the answer. – nims Jul 09 '12 at 20:02
3

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

nick
  • 643
  • 1
  • 5
  • 11
2

If Perl is an option:

perl -lne 'print substr($_,1,6)' file

Output is identical to answer from @nims

Chris Koknat
  • 3,305
  • 2
  • 29
  • 30