3

I would like to extract a user name from the file between the keywords "/" and "NET" like below. How can I do so with programs like awk, sed or cut.

from:

audit: command=true   rsa1/abc.domain.net@xyz.DOMAIN.NET running
audit: command=true   user2/xyz.domain.net@xyz.DOMAIN.NET executing

to:

audit: command=true   rsa1 running
audit: command=true   user2 executing
1
  • sed -e 's#/.* ##' – cuonglm Jun 10 '15 at 16:40
5

Using sed:

< inputfile sed 's/\/.*NET//' > outputfile

Using sed in-place:

sed -i.bak 's/\/.*NET//' inputfile

Command #1 breakdown:

  • < inputfile: redirects the content of inputfile to sed's stdin
  • > outputfile: redirects the content of sed's stdout to outputfile

Command #2 breakdown:

  • -i.bak: Forces sed to create an inputfile.bak backup file and to edit inputfile in-place
  • inputfile: Forces sed to read the input from inputfile

Regex breakdown:

  • s: asserts to perform a substitution
  • /: starts the search pattern
  • \/: matches a / character
  • .*NET: matches any number of any character up to the end of a NET string
  • /: stops the search pattern / starts the replace pattern
  • /: stops the replace pattern

Sample output:

~/tmp$ cat inputfile
audit: command=true   rsa1/abc.domain.net@xyz.DOMAIN.NET running
audit: command=true   user2/xyz.domain.net@xyz.DOMAIN.NET executing
~/tmp$ < inputfile sed 's/\/.*NET//' > outputfile
~/tmp$ cat outputfile 
audit: command=true   rsa1 running
audit: command=true   user2 executing
~/tmp$ sed -i.bak 's/\/.*NET//' inputfile
~/tmp$ cat inputfile.bak
audit: command=true   rsa1/abc.domain.net@xyz.DOMAIN.NET running
audit: command=true   user2/xyz.domain.net@xyz.DOMAIN.NET executing
~/tmp$ cat inputfile
audit: command=true   rsa1 running
audit: command=true   user2 executing
~/tmp$ 
1
  • I like the way you explain these. – mikeserv Jun 10 '15 at 19:07
3

You can try also with awk:

awk '{ split($3, a, "/"); $3 = a[1]; } 1' file
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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