0

This piece of code:

foreach line (`cat /etc/group`)
    echo $line
end

returns line containing 4 fields delimited by :.

How to split fields and access the first field of each line?

2 Answers2

1
foreach line ("`cat /etc/group`")
    set fs = ($line:gas/:/ /)
    set f = ($fs)
    echo "$f[1]"
end

In tcsh you can omit the intermediate fs variable, and directly set f = ($line:gas/:/ /).

The :s/pat/rpl/ variable modifier will replace every occurrence of pat in the variable with rpl (pat is a simple text, no regexps are recognized). The a flag tells to replace all occurrences, and the g flag to do it in all the words.

If using the original csh and the /etc/group file contains glob metacharacters, you'll have to bracket the loop in a set noglob / unset noglob pair.

  • what's gas and why there's an extra slash in gas/:/ / –  Jul 16 '19 at 22:08
  • looks like I've to have a space before the last slash, Is there any online doc to know more about these tricks of csh/tcsh? –  Jul 16 '19 at 22:12
  • 1
    They're in the csh(1) manpage, all those modifiers are described under the "History substitutions" section, since they're similar. –  Jul 16 '19 at 22:17
  • So it's like g for global, a for all and s for substitute, nice! –  Jul 16 '19 at 22:26
0

Use awk with the -F flag. You'll have to use echo and pipe into awk like so:

for line in `cat /etc/group`
do
   col1=$(echo $line | awk -F':' '{print $1}')
   col2=$(echo $line | awk -F':' '{print $2}')

   # Then you can use col1, col2, etc...

   echo "column 1 = $col1"
   echo "column 2 =  $col2"
done
  • I'm looking for a csh/tcsh based solution to this like this. –  Jul 16 '19 at 20:17
  • 1
    ahh, unfortunately bash is my specialty, apologies – Chuck Horowitz Jul 16 '19 at 20:19
  • It's alright, hope this answer would help someone else to solve his/her problem –  Jul 16 '19 at 20:21
  • 1
    That's not even correct Bash/sh syntax (you're missing the in keyword). Even if you correct that, running for line in $(cat file) is just a bad way to do it and only works in this case since /etc/group has little whitespace apart from the newlines. – ilkkachu Jul 16 '19 at 21:32
  • Agreed. Reading files in this way is a pain in bash. Fixed in answer that isn't correct in any case – Chuck Horowitz Jul 19 '19 at 17:53