Saturday, May 18, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1347  / 1 Year ago, mon, december 12, 2022, 11:21:07

I have a file which is like this

user:[dgalanos] rid:[0xa35]
user:[roleary] rid:[0xa36]
user:[smorgan] rid:[0xa37]

How can i print only the usernames like this


I tried

cat users.txt | awk -F  ':' '{print $2 > "users3.out"}'

But it did not give me the correct result i expected.

More From » awk


The most simple way is to modify your command as follows:

awk -F '[' '{print $2}' users.txt | awk -F ']' '{print $1}' > users3.out

  • I'm using two piped awk to catch at first what is after the [ and then what is after the ]. The delimiter are you interested in is not the semiclon, but the brackets.

  • Piping | means that the output of the first command is used as input of the second command. The second awk does not work if you use it alone, but it gets some sense only if you pipe it to the first command.

  • When piping, you don't have to repeat the input file: for this reason in the second awk there is no repetition of the input file users.txt. If you are curious to use the second awk alone, write: awk -F ']' '{print $1}' users.txt

  • You don't need to redirect cat output to awk because awk can accept files as input

  • Your redirection to an output file must not be inside the awk command, but at the end of the full command.

If you want to see the results in the terminal but not in a file, you can remove the part from >

There is a more elegant way to get the data without piping two awk commands but defining the two brackets as delimiters:

awk -F '[][]' '{print $2}' users.txt > users3.out

[#795] Tuesday, December 13, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 354
Total Questions: 105
Total Answers: 124

Location: Iraq
Member since Sat, Apr 3, 2021
3 Years ago
oraoming questions
Fri, Aug 20, 21, 10:08, 3 Years ago
Mon, May 24, 21, 21:56, 3 Years ago
Mon, Sep 12, 22, 11:38, 2 Years ago
Mon, May 30, 22, 01:38, 2 Years ago