12

file is:

BASH.NIR
SH.ABI

I want the awk script to show:

User is NIR, SHELL is BASH
User is ABI, SHELL is SH

I don't know how to split a parameter by char. The idea is:

cat file.txt | awk '{print "User is " afterDot($1) ", SHELL is " beforeDot($1)}'

3 Answers 3

25

You can just use . as the field separator:

awk -F. '{ print "User is " $2 ", SHELL is " $1 }' file.txt
4
  • the text file can also have whitespaces
    – Nir
    Dec 22, 2013 at 15:17
  • 7
    @nir Please paste a sample of your exact input into your question, I can't guess what it looks like unless you represent it properly.
    – Chris Down
    Dec 22, 2013 at 15:18
  • 1
    @nir - it's always best to include real example data. Contrived data usually just wastes the answer's time since it generally leads to the wrong solutions.
    – slm
    Dec 22, 2013 at 15:22
  • you right, will do form next time.
    – Nir
    Dec 23, 2013 at 7:13
3

You can use the string functions in awk.

$ (echo BASH.NIR; echo SH.ABI FOOBAR) | awk '{p=index($1,".");print "User is", substr($1,p+1) ", SHELL IS", substr($1,0,p-1)}'
User is NIR, SHELL IS BASH
User is ABI, SHELL IS SH

The index function returns the position of the character to be found (in this case a dot) and substr will return a substring. We use p+1 and p-1 to not include the dot.

For more information look in the "String Functions" section of the awk manpage.

0
0

not as elegant as I hoped but it got the job done :

echo "BASH.NIR\nSH.ABI" \
 \
 | mawk 'sub( /$/,  ", SHELL is " ($!_=$!_))+\
         sub(/^[^ ]* /,"User is ")' FS='[.]'

User is NIR, SHELL is BASH
User is ABI, SHELL is SH

Only can confirm it works for gawk, mawk-1, and mawk-2. Can't get nawk onboard.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.