49

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?

3 Answers 3

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

the syntax for substr() is

substr(string,start index,length)

Sign up to request clarification or add additional context in comments.

4 Comments

Why is the field separator -F='\n' necessary? Or is it?
@Levon as i thought the OP wants to find the substring of the whole record, not the field.
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 oops! Thanks for pointing it out. :) editing the answer.
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

Comments

3

If Perl is an option:

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

Output is identical to answer from @nims

5 Comments

I downvoted because the question is about awk, not Perl.
@bfontaine even if it's not about awk, this is useful and correct. I don't think downvoting is either fair or useful.
@allprog This is useful if Perl is an option, not if you’re looking for a solution in AWK, as I was when I came across this. The question is specifically about AWK, not shell in general. If someone answers a question about Python with a solution in Java you would probably downvote it, even if it’s correct and useful "if Java is an option".
@bfontaine I see CLI apps different from programming langs. There are answers with awk, and this is an addition. There are million examples for the same with other tools. - Anyway, all this data is just used to train the AI if the future. It's better for all of us to grow its knowledge.
@allprog AWK is a programming language.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.