使用csh将命令的结果存储到变量中

时间:2015-11-05 00:00:10

标签: unix csh

我试图将一个命令的结果存储到一个变量中,这样我可以很好地显示它,并且在一个长的文本中没有显示输出,然后在我的csh脚本中显示新文本。

#! /bin/csh -f


if ("$1" == "-f" && $#argv == 1 ) then
    grep 'su root' /var/adm/messages.[0-9] | cut -c 21-250
    grep 'su root' /var/adm/messages
else if( $#argv >  0 ) then
    echo "Usage : [-f]"
else
  grep 'su root' /var/adm/messages.[0-9] /var/adm/messages | wc -l
  printf "failed su attempts between Nov 02 and Oct 28\n"
endif

脚本中的这个命令

  grep 'su root' /var/adm/messages.[0-9] /var/adm/messages | wc -l
当我运行它时,

给了我21,我希望21存储在一个变量中。

所以我只能显示

的输出
21 failed su attempts between Nov 02 and Oct 28

而不是

21
failed su attempts between Nov 02 and Oct 28

或者如果这是一种更简单的方式,也不会涉及变量。

1 个答案:

答案 0 :(得分:2)

您可以使用using System.Linq; public static class StringExtensions { /// <summary> /// Returns a string array that contains the substrings in this instance that are delimited by specified indexes. /// </summary> /// <param name="source">The original string.</param> /// <param name="index">An index that delimits the substrings in this string.</param> /// <returns>An array whose elements contain the substrings in this instance that are delimited by one or more indexes.</returns> /// <exception cref="ArgumentNullException"><paramref name="index" /> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">An <paramref name="index" /> is less than zero or greater than the length of this instance.</exception> public static string[] SplitAt(this string source, params int[] index) { index = index.Distinct().OrderBy(x => x).ToArray(); string[] output = new string[index.Length + 1]; int pos = 0; for (int i = 0; i < index.Length; pos = index[i++]) output[i] = source.Substring(pos, index[i] - pos); output[index.Length] = source.Substring(pos); return output; } } 和反引号(``)。像

这样的东西
set

set count=`grep 'su root' /var/adm/messages.[0-9] /var/adm/messages | wc -l`
printf "$count failed su attempts between Nov 02 and Oct 28\n"
没有变量的

,例如

printf "%s failed su attempts between Nov 02 and Oct 28\n" "$count"