I have a trouble in separating few exact ‘fields’ with strings and then putting them into .txt file. I need to extract ‘nologin’ users from /etc/passwd file and that is an easy step. I’m using this command:
grep -n 'nologin' /etc/passwd > file1.txt
cat command gives me for example:
2:daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin 3:bin:x:2:2:bin:/bin:/usr/sbin/nologin 4:sys:x:3:3:sys:/dev:/usr/sbin/nologin
and it is saved to file1.txt
Now I have to extract from file1.txt a number (2, 3, 4), login (daemon, bin, sys) UID and shell. It should look like this
2:daemon:1:/usr/sbin/nologin 3:bin:2:/usr/sbin/nologin 4:sys:3:/usr/sbin/nologin
I also have to save that output to a *.txt file. How can I achieve this?
Advertisement
Answer
You can use the cut command like this:
cut -d':' -f1 file1.txt > file2.txt
According to the man page:
-d, –delimiter=DELIM
use DELIM instead of TAB for field delimiter
-f, –fields=LIST
select only these fields; also print any line that contains no delimiter character, unless the -s option is specified