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?
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?
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.
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
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
gasand why there's an extra slash ingas/:/ /– Jul 16 '19 at 22:08csh/tcsh? – Jul 16 '19 at 22:12gfor global,afor all andsfor substitute, nice! – Jul 16 '19 at 22:26