I work for a small ISP and we are using Unix operating system with bash shell. I want to write a shell script to parse the csv file line by line. Then line must be parse again field by field. The sample input file is as follows:
I need to extract each of these example.com,username,groupname,homedir,md5password,permission,secondarygroup and passed to the different system utilities. How do I write a shell script to automate this task and use the bash shell parse a text file?
You can use the bash while loop and read builtin commandas follows:
#!/bin/bash input="/path/to/your/input/file.cvs" # Set "," as the field separator using $IFS # and read line by line using while read combo while IFS=',' read -r f1 f2 f3 f4 f5 f6 f7 do echo "$f1 $f2 $f3 $f4 $f5 $f6 $f7" done < "$input"
You can pass f1, f2 and other fields as per your requirements to other Unix commands:
#!/bin/bash input="/path/to/your/input/file.cvs" while IFS=',; read -r f1 f2 f3 f4 f5 f6 f7 do /path/to/useradd -d "$f4" "$f2" done < "$input"
The IFS is a special shell variable. The Internal Field Separator (IFS) that is used for word splitting after expansion and to split lines into words with the read builtin command.
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop