有没有一种方法可以找到模式的中间并在bash中将其小写

时间:2019-05-10 12:50:45

标签: bash

我正在努力减少文本数据的大小。

示例输入:

example@EXAMPLE.com;example
example@EXAMPLE.com:exmaple

示例输出:

example@example.com;example
example@example.com:exmaple

伪代码:

if line has "@" and ":" or ";"
replace the text between @ and : or ; with lowercase

但是我什至不知道要使用什么工具。欢迎任何帮助。

2 个答案:

答案 0 :(得分:0)

使用 sed 工具解决此问题,

cat input_file.txt | sed -e 's/\(.*@\)\([A-Za-z.]\+\)\([;:].*\)/\1\L\2\3/' 

正则表达式说明:

  

\(。* @ \)-此模式与“ example @”匹配

     

\([[A-Za-z。] \ + \)-匹配“ EXAMPLE.com”的模式

     

\([;:]。* \)-匹配“:exmaple”或“; exmaple”的模式

     

\ L 更改为小写文本

如果要更新内容,请在sed命令中使用 -i 标志。

Ex:

sed -i -e 's/\(.*@\)\([A-Za-z.]\+\)\([;:].*\)/\1\L\2\3/' input_file.txt

答案 1 :(得分:0)

如果有很多数据,awk将比Shell更快。 sed解决方案很好,但是也可以:

$: awk '-F[;:]' '{ printf "%s;%s\n", tolower($1), $2 }' x
example@example.com;exaMple
example@example.com;eXmaple
example@example.com;exAmple
example@example.com;exmaplE
example_example.com;Example
example_example.com;eXmaple
example@example.com,example;

这将-F分隔符定义为;:的列表,并小写第一个字段。我随便用标准的;替换了分隔符-如果这样不起作用,那么这可能不是您的最佳解决方案。坚持使用sed

  我最初输入时,

sprabhakaran用几乎相同的sed解决方案击败了我,大声笑。 :)

sed可以。

$: cat x
Example@EXAMPLE.cOm;exaMple
exampLe@EXAMPLE.coM:eXmaple
example@EXAMPLE.com;example
example@EXAMPLE.com:exmaple
example_EXAMPLE.com;example
example_EXAMPLE.com:exmaple
example@EXAMPLE.com,example

$: sed -E '/@.+[;:]/s/^(.*)@(.*)([;:])(.*)/\1@\L\2\E\3\4/' x
Example@example.com;exaMple
exampLe@example.com:eXmaple
example@example.com;exAmple
example@example.com:exmaplE
example_EXAMPLE.com;Example
example_EXAMPLE.com:eXmaple
example@EXAMPLE.com,examPle

\L说开始小写,直到\E(结束)或\U(开始大写)为止。

这会跳过同时没有@[;:];:都没有的行)

  

对于原生bash的小型数据集,可能会更容易。

然而,仅对整个内容进行小写化可能要简单得多。

$: declare -l line
$: while read line
> do echo "$line"
> done < x
example@example.com;example
example@example.com:exmaple
example@example.com;example
example@example.com:exmaple
example_example.com;example
example_example.com:exmaple
example@example.com,example

declare -l使变量始终小写。


由于区分大小写的密码可以防止这种情况,请分别解析各个部分。

$: while IFS="$IFS:;" read email pass
> do echo "$email [$pass]"
> done < x
example@example.com [exaMple]
example@example.com [eXmaple]
example@example.com [exAmple]
example@example.com [exmaplE]
example_example.com [Example]
example_example.com [eXmaple]
example@example.com,example []

只要记录格式正确,它就可以很好地工作。 我认为您可以检查错误或信任您的数据。