Regex Shell:从文件中选择小写单词,对它们进行排序并复制到另一个文件中

Regex Shell:从文件中选择小写单词,对它们进行排序并复制到另一个文件中,regex,shell,unix,Regex,Shell,Unix,我想制作一个shell脚本,从命令行获取两个参数,第一个应该是现有文件,另一个是新文件,它将包含结果。从第一个文件中,我想选择小写单词,然后对它们进行排序,并将结果复制到第二个文件中。grep命令显然不好,我应该如何更改它以获得结果 #!/bin/bash file1=$1 file2=$2 if [ ! -f $file1] then echo "this file doesn't exist or is not a file break else grep '/[a-

我想制作一个shell脚本,从命令行获取两个参数,第一个应该是现有文件,另一个是新文件,它将包含结果。从第一个文件中,我想选择小写单词,然后对它们进行排序,并将结果复制到第二个文件中。grep命令显然不好,我应该如何更改它以获得结果

#!/bin/bash
file1=$1
file2=$2
if [ ! -f $file1]
then
    echo "this file doesn't exist or is not a file
    break
else
    grep '/[a-z]*/' $file1 | sort > $file2

我很赶时间,所以我不会重写我在评论中指出的内容,但下面是您的代码,所有这些问题都已修复:

#!/bin/bash
file1=$1
file2=$2
if [ ! -f $file1 ]
then
    echo "this file doesn't exist or is not a file"
else
    grep '[a-z]*' $file1 | sort > $file2
fi
ShellCheck还提供了一个提示,你一定要申请,我让你看看


当脚本无法执行其任务时,也就是在找不到文件的情况下,使用非零代码退出也是一种很好的做法。

您可以这样更改grep命令:

grep -o '\<[[:lower:]][[:lower:]]*\>' "$file1" | sort -u > "$file2"
grep-o'\'“$file1”| sort-u>“$file2”
o是一个输出控制开关,它强制grep以换行方式返回每个匹配项

\
是右侧单词边界。(这样,单词
站点
就不会返回
站点

[[:lower:][[:lower:][]*
确保至少有一个小写字母。
(最好使用
[[:lower:][]
而不是范围
[a-z]
,因为在某些地区,字母可能按字母顺序排列,而不考虑大小写:
abbcdd…yyz


注意:我在sort命令中添加了-u开关以删除重复的条目,如果您不希望出现这种行为,请删除它。

使用awk和
sort
,首先是测试文件:

$ cat file
This is a test.
This is another one.
代码:


我使用空格、换行符和句点作为记录分隔符,将每个单词作为自己的记录分开,并打印只包含小写字母的单词。

您的shell代码可能需要一些修正

#!/bin/bash
file1=$1
file2=$2
if [ ! -f "$file1" ] # need space before ]; quote expansions
  # send error messages to stderr instead of stdout 
  # include program and file name in message
  printf >&2 '%s: file "%s" does not exist or is not a file\n' "$0" "$file1"
  # exit with nonzero code when something goes wrong
  exit 1
fi

# -w to get only whole words
# -o to print out each match on a separate line
grep -wo '[a-z][a-z]*' "$file1" | sort > "$file2"

如果同一单词在文件中多次出现,则包含该单词的多个副本;如果您不想这样做,请更改为
sort-u

修复代码块格式,在缺少的结束引号下加下划线。在
if
的条件下,在结束括号前还应该有一个空格。
中断
if/then/else/fi
块中没有意义,您缺少
fi
。grep几乎没有问题,但是,
/…/
是一个JavaScript构造:您需要删除斜杠。您可能想查看一个可以粘贴代码并指出此类错误的网站。还需要
grep-wo
仅选择字符。我现在就知道了。谢谢:)这里的
$file1
$file2
都应该在双引号内。
#!/bin/bash
file1=$1
file2=$2
if [ ! -f "$file1" ] # need space before ]; quote expansions
  # send error messages to stderr instead of stdout 
  # include program and file name in message
  printf >&2 '%s: file "%s" does not exist or is not a file\n' "$0" "$file1"
  # exit with nonzero code when something goes wrong
  exit 1
fi

# -w to get only whole words
# -o to print out each match on a separate line
grep -wo '[a-z][a-z]*' "$file1" | sort > "$file2"